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,849,359
69,850,769
Is it correct to resize a vector with moved-elements?
I am trying to understand the generic rules of move semantics. Specifically of containers and contained elements. The reason is that I am trying to understand move in the context of ownership and iterator invalidation. To do that I am going through some cases with increasing complexity involving a typical container, a ...
std::vector<T> v(100, t); f(std::move(v)); v.resize(120); is similar to your case 1 std::vector<T> v(100, t); f(std::move(v)); g(v); vector::resize has no prerequires, but you don't know previous state. it might be empty, have some size (with unspecified value). So after v.resize(120), you just know that the new size...
69,849,438
69,849,599
Exception thrown: read access violation. **this** was 0xCCCCCCCC
I'm trying to build an understanding of objects, arrays, and pointers. When I compile my code I ended up with 0xCCCCCCCC. I understand that this error is probably due to an uninitialized pointer. The problem is I don't know where or how to. #include <iostream> #include <string> using namespace std; class Person { publ...
The Problem is you have an Array of Person Person* person[] pointers and not an array of persons. I fixed the code and removed the pointers: #include <iostream> #include <string> using namespace std; class Person { public: string name; }; void createPerson(Person person[]); int main() { Person person[5]; cre...
69,849,548
69,849,573
Are there any differences between accumulate(a.begin(), a.end(), 0) and accumulate(a.begin(), a.end(), 0ll) in C++?
When I write long long sum = accumulate(a.begin(), a.end(), 0); or long long sum = accumulate(a.begin(), a.end(), 0ll); both give me the same result (where a is std:: vector<int> a(n)). So why use 0ll instead of only 0 ? Here is my code: #include <bits/stdc++.h> using namespace std; const int MAX = 1e6; int main() { #i...
std::accumulate is a template, when being passed 0 (which is supposed to be the initial value of the sum), the 2nd template parameter will be deduced as int, then the sum is performed on int, the return type is int too. Then in long long sum = accumulate(a.begin(), a.end(), 0);, the returned int is converted to long lo...
69,849,844
69,849,901
Can I insert a vector to itself with std::vector::insert?
Is it allowed by the C++03 standard to append a std::vector to itself? I wonder if the source iterators can become invalid if v needs to reallocate memory. In my STL implementation, the old memory is kept until the new memory has been created. But can I rely on this? If not, is v.reserve(2 * v.size()) before the insert...
Regardless of whether perform reserve in advance or not, the behavior is undefined. For std::vector::insert: inserts elements from range [first, last) before pos. The behavior is undefined if first and last are iterators into *this.
69,850,402
69,850,921
How to convert this directory "engine\\..\\..\\NewFolder" to absolute directory ( C++ Window )
How to convert this directory "c:\~~\engine\..\..\NewFolder" to absolute directory. I have some directory string containing "\..\". I don't know how to convert this to real path. I'm on C++, Windows.
There's a function for this called PathCanonicalize() in the Win32 API which you might find useful. Example usage: TCHAR outbuf [32767]; PathCanonicalize (outbuf, my_path); outbuf is as long as it is to handle long path names, which is a user-definable option in Windows 10 and later. You can, of course (and probably ...
69,851,029
69,851,065
how to specify constructor in header for child and parent class
I am new to C++ and define a parent class in a header file parent.h. It has a constructor Parent(int a, int b). Now I want to write the header file for the child class child.h, which inherits the exact same constructor as the parent class and only has additional member functions. Do I have to specify the constructor in...
Constructors aren’t inherited. Therefore, if you want your child class to have the specified constructor you will need to provide it explicitly inside your class definition: … Child(int a, int b) : Parent(a, b) {} … Or pull in the definition from the parent class: using Parent::Parent; Note that this will pull in all...
69,851,551
69,851,675
Call templated class with multiple parameters with single parameter only
I have a class with multiple template parameters; let us say it looks something like this: template <class T, class B> struct Vector2 : B { Vector2() noexcept; constexpr explicit Vector2(T a) noexcept; } Template parameter B always depends on T. For example if T is float B will be XMFLOAT2, if T is int B will ...
You can create helper trait: template <typename T> struct vector_base_class; template <> struct vector_base_class<float> { using type = XMFLOAT2; }; template <> struct vector_base_class<int32_t> { using type = XMINT2; }; template <> struct vector_base_class<uint32_t> { using type = XMUINT2; }; template <class T> stru...
69,851,868
69,855,886
How does gdb find the address of a variable in anonymous namespace
I have a variable declared in a c++ file like this: namespace { VelocityLongitudinal vel_lgt; } The corresponding dwarf info is <1><5e08b>: Abbrev Number: 317 (DW_TAG_namespace) <5e08d> DW_AT_sibling : <0x5e09e> <2><5e091>: Abbrev Number: 193 (DW_TAG_variable) <5e093> DW_AT_name : (indirect...
How does gdb find that? By reading the symbol table (equivalent to what readelf -s does), in addition to reading the debug info. It seems unlikely that gdb would search for entries with matching last characters It doesn't. The name you found demangles to (anonymous namespace)::vel_lgt (except you appear to have mad...
69,852,735
69,852,912
How does the auto keyword deduct the type in C++
I wonder how the auto keyword determines the type of a variable in c++. I thought that statically typed languages couldn't do that. For example, how does this work: #include <iostream> int main() { std::cout << "Hello World!\n"; auto a = 5433245244524; std::cout << a << std::endl; }
It works in same way as deduction of expression returning type for templates. It happens at compilation type, so it is a static type. Literal 5433245244524 comprises initializing expression. You can get the type of expression at compile time (static type) by using operator decltype(). E.g. decltype(5433245244524) a =...
69,852,815
69,867,365
Unable to print other levels via BOOST_LOG_SEV
I'm trying to use Boost.Log but when I use: BOOST_LOG_SEV(slg, level)//Doesn't matter the level here even if manually pass error I'm always getting: [2021-11-05 12:07:01.305178] [0x00007ffff21589c0] [info] I'm expecting [info] to reflect the severity level I'm passing. [Edit] This is the code (Entire code, from .hpp)...
I suspect, you're using a severity level type different from boost::log::trivial::severity_level while still relying on the default sink. If the default sink can't extract severity level from a log record, it will use boost::log::trivial::severity_level::info as a default. You should either use boost::log::trivial::sev...
69,854,268
69,854,507
GLSL - Calculate the surface normal given its vertex normal
I want to implement flat shading on OpenGL. I googled it and found this question: How to achieve flat shading with light calculated at centroids?. I understood the top answer idea and I'm trying to implement it. However, I couldn't figure out how to find the surface normal given the normals of each vertex of the triang...
The surface normal can be computed with the Cross product of 2 vectors on the surface. The following code is for counter-clockwise triangles: vec3 v1 = vertexP[1] - vertexP[0]; vec3 v2 = vertexP[2] - vertexP[0]; vec3 surfNormal = normalize(cross(v1, v2)); If the winding order of the triangles is clockwise, you have to...
69,855,772
69,917,577
Can a lock-free atomic write / consistent read operation be achieved on a 4 byte int using System V shared memory across language platforms?
I want to implement a lock free counter, a 4-byte int, in System V shared memory. The writer is a C++ program, the reader is a Python program. Working roughly like this: C++ code updates counter in an atomic operation Python code reads counter and has a consistent view of memory (eventual consistency is perfectly acce...
Yes, using the atomics library, along with a suitable shared memory library (e.g. mmap or shared_memory). This example assumes your atomic int is in the first 4 bytes of the shared memory segment. from atomics import atomicview, MemoryOrder, INT from multiprocessing import shared_memory # connect to existing shared m...
69,855,859
69,855,935
Compile time errors while implement Virtual Functions and Run-time polymorphism in C++
I created the following program to implement Run-time Polymorphism in C++ /* Consider a book shop which sells both books and video-tapes. Create a class know as media that storea the title and price of a publication.*/ #include <iostream> #include <cstring> using namespace std; class media // defining base class { pr...
The problem is instead of declaring the function display inside class book and tape you were defining them because you have curly braces {}. And then you again redefined them outside the class. To solve this, just replace: void display() {} with void display() ; in class book and tape. So your class book and tape wou...
69,856,425
69,857,216
free(): double free detected in tcache 2 on calling assignment operator
I've just asked a very similar question, but I've been over the answers to that one and I just can't see what I'm doing wrong this time around. I'm working on a university project implementing the c++ list<int> using a linked list. I'm working on the assignment operator, and here's what I have so far. Linkedlist &Linke...
The line: Linkedlist b = a; calls copy constructor, not assignment operator. If you didn't provide copy constructor, then the compiler-generated one will just copy head pointer. Then, during destruction the same head will be deleted both from list a and list b leading to "double free".
69,856,792
69,859,627
Winsock connect fails with WSAEFAULT | Error on Windows 11 only
My code perfectly works on any Windows from XP to 10. Now I've tested my code for the first time in Win11, and the connect() function fails with error 10014 WSAEFAULT: Bad address. The system detected an invalid pointer address in attempting to use a pointer argument of a call. This error occurs if an application pass...
As noted in the comments, your code is not IPv6 aware. Windows 11 ships with IPv6 enabled by default. You should update your code to be IPv4 vs. IPv6 agnostic. See Microsoft Docs. Note Microsoft stop shipping checkv4.exe ages ago, but if I run it against your code I get: sockaddr_in : use sockaddr_storage instead, or u...
69,856,891
69,856,983
C++ including Python.h compiling using makefile
I am trying to compile a C++ program which uses Python.h to execute some python scripts. Before adding the python, I had a makefile which works perfectly. I added the code to run the python script, which involves including the Python.h file. I edited the makefile to include this file, without success. My makefile: CC ...
You are mixing C and C++. These are completely different languages: you shouldn't confuse them. In makefiles, the default rules use CC to hold the C compiler and CXX to hold the C++ compiler. Similarly, they use CFLAGS to hold flags for the C compiler and CXXFLAGS to hold flags for the C++ compiler. In your makefile ...
69,857,081
69,863,213
how could I use the power function in c/c++ without pow(), functions, or recursion
I'm using a C++ compiler but writing code in C (if that helps) There's a series of numbers (-1^(a-1)/2a-1)B^(2a-1) A and X are user defined... A must be positive, but X can be anything (+,-)... to decode this sequence... I need use exponents/powers, but was given some restrictions... I can't make another function, us...
It is a series. Replace pow() based on the previous iteration. @Bathsheba Code does not need to call pow(). It can form pow(x, 5 * i - 1) and pow(-1, i - 1), since both have an int exponent based on the iterator i, from the prior loop iteration. Example: Let f(x, i) = pow(x, 5 * i - 1) Then f(x, 1) = x*x*x*x and f(x...
69,857,124
69,913,213
Can we use auto keyword instead of template?
Can we use auto keyword instead of template? Consider following example : #include <iostream> template <typename T> T max(T x, T y) // function template for max(T, T) { return (x > y) ? x : y; } int main() { std::cout << max<int>(1, 2) << '\n'; // instantiates and calls function max<int>(int, int) std::co...
Finally I found the answer to my question: We can use abbreviated function templates if we're using the C++20 language standard. They are simpler to type and understand because they produce less syntactical clutter. Note that our two snippets are not the same. The top one enforces that x and y are the same type, wherea...
69,857,519
69,863,090
Taking input from editbox as displaying the result
I am currently working on an MFC C++ program that takes a mathematical expression as input and displays the result. But I am having trouble reading from the editbox. The code for taking in input and displaying it is as below: { char input[50]; sprintf_s(input, "%d", IDC_EDIT1); len = strlen(input); ...
You want this: { CString input; GetDlgItemText(IDC_EDIT1, input); len = input.GetLength(); ... CString s; s.Format(_T("%.2f"), mCurVal); SetDlgItemText(IDC_EDIT1, s); } Forget char arrays like char input[50]; if you're using MFC, you can use CString almost all the time instead.
69,857,528
69,857,689
C++20 Likely and UnLikely?
I was reading https://iq.opengenus.org/cpp-likely-and-unlikely-attributes/ and I don't understand/agree with few things. In the following code: void doModulus( vector<int> &vec , int mod ){ // here the value of mod we are passing is 224, vec is of size 1024 holding values in [1,255] for( int i = 0 ; i<vec.size()...
does it matter or make any difference if we make the else code [[likely]] or this happens automatically in background as if one side is likely then the other side isn't? The C++ Standard say about likely just recommended practice and example. See [dcl.attr.likelihood]. So it is up to the implementation how they are a...
69,857,618
69,865,933
fmt::dynamic_format_arg_store replacement/implementation for std::format
It looks like that c++20 std::format is not a direct replacement for the fmt library. Looking at the API (https://en.cppreference.com/w/cpp/utility/format) it looks like that fmt::dynamic_format_arg_store is not part of the standard. Currently in fmt you can have the following code: #include <fmt/format.h> #include <fm...
You cannot portably implement an equivalent of fmt::dynamic_format_arg_store for std::format yourself because the representation of std::basic_format_args is an implementation detail of the standard library. It might be provided in one of the future versions of the C++ standard.
69,858,031
69,858,197
Create std::list unique_ptr from variadic template
I try to create std::list from args, but when pass more than 0 params get an error "no matching function for call to 'make_unique'". I think that the mistake is that I pass all the arguments to make_unque at once, but I do not understand how to open the bundle 2 times. template<class ...Args> void do(Args&&... args) { ...
Syntax would be: template<class ...Args> void do(Args&&... args) { std::list<std::unique_ptr<Base>> obj{std::make_unique<Child>(std::forward<Args>(args))...}; } but you cannot move elements from std::initializer_list (their element are const). A possible workaround is to emplace: template<class ...Args> void do(Ar...
69,858,137
69,858,537
What type of filter is this?
output = (((previous * rate) + current) / (rate + 1.0)) I believe it's a low pass, but correct me if I'm wrong. Is there a more accurate way to describe a function like this?
This is a low pass filter, with an Infinite Impulse Response design. The rate is used to determine how much a single new value can change the output. A large rate puts more value on the previous state, and less on the current value. Consider when rate is 1: output is 1/2 of the previous value plus 1/2 of the current va...
69,858,189
69,858,955
CMake can't find file or directory
I'm working on a CMake project with multiple subdirectories and I can't get it to work. My working directory is the following: ├───main.cpp ├───CMakeLists.txt ├───build ├───States └───CMakeLists.txt └───Elevator ├───CMakeLists.txt Once I build the project, I get Elevator/Elevator.h: No such file or directory a...
For #include "Elevator/Elevator.h" to work in the States library you need to include the folder containing the Elevator folder. One way to fix this is to change target_include_directories(States PUBLIC ${CMAKE_CURRENT_LIST_DIR}) to target_include_directories(States PUBLIC ${CMAKE_CURRENT_LIST_DIR} ${CMAKE_CURRENT_LIS...
69,858,292
69,858,452
I am working on airline management system. Here User enters the selected destination from shown destinations,so it's showing INVALID DESTINATION
string dest; string local_des[4]={"HYDERABAD","KOLKATA","GWALIOR","DELHI"}; string inter_des[5]={"USA","PARIS","DUBAI","LAS VEGAS","LONDON"}; char option; cout<<"\nPlease select your destination type:\n"; cout<<"1.Local Destinations\n"; cout<<"2.International Destinations\n"; cout<<"\nENTER YOUR CHOICE(1 or 2)\n"; cin>...
You will want to fix this loop: for (int j = 0; j < 5; j++) { if (dest == inter_des[j]) { stat = 1; } else { stat = 0; // Resets stat to 0 } } Currently stat will be 0 unless the last item in the inter_des was the same as dest. That is because every time that dest is not matched to the...
69,858,324
69,858,529
Are there any pitfalls to using std::move() in value-oriented property setter?
I came across this answer to how to write C++ getters/setters and the author implies that when it comes to value-oriented properties, the setters in the standard library use the std::move() like this... class Foo { X x_; public: X x() const { return x_; } void x(X x) { x_ = std::move(x); } } (code taken di...
Yes there is. Receiving a parameter by value and move is okay if you always send an rvalue to that parameter. It is also okay to send an lvalue, but will be slower than receiving by const ref, especially in a loop. Why? It seem that instead of making a copy you simply make a copy and then move, in which the move in ins...
69,858,579
69,858,810
Why does >> operator gives error on const file in C++?
I have this piece of code: void NeighborsList::insertVertexes(const ifstream & inputFile) { int tempS, tempT; for (int i = 0; i < numOfVertexes; i++) { inputFile >> tempS; inputFile >> tempT; addEdge(tempS, tempT); } } where I'm trying to get the input for a file. Once I remove ...
Given a const object or reference, only const operations may be performed. std::istream::operator>> is not a const operation, therefore it may not be used here. It makes sense that std::istream::operator>> is not a const operation, because it alters the observable state of the stream. The read position on the file is c...
69,859,146
69,859,554
What does `class function<_Res(_ArgTypes...)>` mean?
The code of std::function in gcc has these two lines: template<typename _Res, typename... _ArgTypes> class function<_Res(_ArgTypes...)> // <-- unclear to me The first part template... _ArgTypes denotes a "parameter pack", i.e., a variadic number of template parameters; that is clear. But the second line is magic. OK...
I think you are confused about the declaration syntax (which is inherited from C language): here, the syntax void(int) does not mean that a function named void and taking an argument named int is being called. Instead, it denotes a type, which is a function, taking a parameter of type int and returning void. You can re...
69,859,683
69,859,810
Assigning a reference to a struct
I have a variable ntot_sols who's final value isn't known when my object is constructed. Consequentially I want to store a reference to the variable instead of the value since it's subject to change. I think the following code will do it. struct ItemWeighter { int nsols; int ntot_sols; ItemWeighter(int _nsols...
You can't use the assignment operator to bind a reference. It has to be bound when first created. For a class member variable, this means you have to do it in a member initializer list; the body of the constructor is too late. Example: #include <iostream> class foo { private: int& x; public: foo(int& other_...
69,859,805
69,885,842
Consequences of and alternatives to use std::forward on non-forwarding-reference type template parameter
I am writing a factory. Both "interface" and the "implementation" are defined by template classes. #include <memory> template<class I, class ...Args> struct IFactory { virtual std::unique_ptr<I> Create(Args... args) = 0; }; template<class I, class C, class ...Args> struct Factory : IFactory<I, Args...> { std::uni...
If a template argument is deduced other than from a forwarding reference, it is never deduced as a reference: then std::forward<T> is just the overload set T&& forward(T&); T&& forward(T&&); which behaves exactly like std::move. If the function parameter was declared as T&, this is misleading: the argument will be mo...
69,860,863
69,899,951
Non-type template parameter specialization
When I compile with GCC it requires switch (A) to be set, while MSVC and Clang can't find MyType specialization and vice versa. Who is right? template <std::size_t col_size, auto val> struct sized_t2 { // static constexpr std::size_t size = col_size; // static constexpr auto value = val; using type = declty...
This is a GCC bug: decltype applied to a template parameter gives the (adjusted, deduced) type of the parameter, not of the (const-qualified) template parameter object to which the parameter name refers as an expression if it is of class type ([dcl.type.decltype]/1.2). Extra parentheses may be used as usual to obtain ...
69,860,976
69,861,386
C++ String Segfault on RHEL 8 with flto (but not RHEL 7)
I have this sample code: # CMakeLists.txt cmake_minimum_required(VERSION 3.18) project(RHBuildTest CXX) message(STATUS "C++ Compiler: ${CMAKE_CXX_COMPILER}") add_executable(script1 script1.cpp) set_target_properties(script1 PROPERTIES COMPILE_FLAGS "-flto") // script1.cpp #include <string> #include <iostream> int...
This is a known bug in RHEL: Segfault when -flto is used to compile Catch framework tests on RHEL 8.4 To confirm that's the same bug you're running into, see if temporarily downgrading binutils to 2.30-79.el8 makes it work. If so, then it looks like it will be properly fixed when RHEL 8.5 is released. (EDIT: I just con...
69,861,396
69,861,629
How replicate eigen::matrix dynamically
During calculating the distance matrix between two feature maps. A:(M,1) B:(N,1) I want to repeat B columns to equal A rows. It is simple in NumPy: A = np.random,rand(100, 1) B = np.random.rand(88, 1) np.repeat(B, A.shape[0], axis=1) But in c++ Eigen, not work for dynamically assigning repeated shapes. MatrixXi A = M...
The correct way to achieve the same effect as the python's numpy version in C++ would be: B.replicate<1, 100>(); The above will do the replication as you want. Or you can use: B.replicate(1, A.rows());
69,861,500
69,876,457
Making a POST request in C++ with curlpp
I am attempting to make a POST request using curlpp in C++ to Statistics Canada with their getDataFromVectorsAndLatestNPeriods. I can't seem to get a result from the request. #include <stdlib.h> #include <stdio.h> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> int main() { cu...
I haven't used libcurlpp, but for libcurl a natural way of making a POST request is through the CURLOPT_POST and CURLOPT_POST_FIELDS options, see for example How to use libcurl for HTTP post?. This leas to this simple main: int main() { curlpp::Cleanup cleanup; curlpp::Easy request; request.setOpt(curlpp::optio...
69,861,537
69,861,936
Catching an exception type with constructor from not-const reference in C++
Consider a struct A with copy-constructor deleted but having instead the constructor from not-const reference. Can one throw an object of A and then catch it by value as in the example program: struct A { A() {} A(A&) {} A(const A&) = delete; }; int main() { try { throw A{}; } catch( A ...
This is an MSVC bug: exception objects are never cv-qualified, and handler variables are initialized from an lvalue that refers to them. (The standard doesn’t actually say what the type of that lvalue is, but there’s no reason it should be const-qualified.)
69,861,548
69,861,567
How does nodejs understand/read c++ code?
I clearly understand Javascript only. I am curious about how Node.js understand C++ code as they are completely different things. How do they communicate with each other?
Using language bindings. The JS interpreter is able to import and call into exported linker symbols from a library, and with language bindings you can provide these, e.g by writing some functionality in C++.
69,861,573
69,869,264
Is there a way to select a single column in a matrix within armadillo?
Is there a way to select all the elements within a column in a matrix in C++ armadillo library? For example, in MATLAB, I can use : to refer to all the elements within a column of the matrix: A = ones(5,5); A(:,1) = A(:,1) * 5; Here, I have choose to multiply by 5 all elements within column 1. A = 5 1 ...
To multiply the fist column of matrix A by 5, use A.col(0) *= 5. The documentation has a syntax conversion table between Armadillo and Matlab. The documentation also describes the many forms of submatrices.
69,861,666
69,861,697
How to overload + operator that can work on objects of class largeIntegers that can store a number upto 100 digits in an array?
I'm learning Data Structures from a book named "Data Structures using C++" by D.S. Malik. I am currently solving the below written programming exercise: In C++, the largest int value is 2147483647. So an integer larger than this cannot be stored and processed as an integer. Similarly, if the sum or product of two posit...
The problem is that your overloaded operator+ was returning a reference to a local variable. To solve this, you can instead use the following version of operator+: //return by value largeIntegers operator+(const largeIntegers &lhs, const largeIntegers &integer) { largeIntegers temp; int remainder = 0; int digi ...
69,861,671
69,861,819
Why does my code not work if I switch the position of commented line on top of the function? It's a memoization recall statement
I'm trying to memoize this unique paths grid problem. Until now, I always put the memoized return statement on top of the function. But here, it's not working. I don't understand why. Do those positions matter sometimes? Can you please explain the reason? I have just started dynamic programming. int grid(long long i, l...
int grid(long long i, long long j, long long m, long long n, vector<vector<long long>> &memo) { // delete the first statement if (i == m - 1 && j == n - 1) return 1; if (i >= m || j >= n) return 0; if (memo[i][j] != -1) return memo[i][j]; memo[i][j] = grid(i + 1, j, m, n, memo) + grid(i, j + 1, m, ...
69,861,865
69,861,919
Seeking helps in explanation of syntax for var[x[n]]
How does the below syntax work? class Solution { public: int lengthOfLongestSubstring(string s) { const int n = s.length(); int ans = 0; // Set a variable as the answer; for(int i = 0; i < n; ++i) { vector <int> seen(128); int j = i; ...
Case 1 s[j] The above means the element at index j of the string named s. Case 2 seen[s[j]] The above means the element at index s[j] of variable named seen. Case 3 seen[s[j++]] = 1; For the above you have to know about the post-increment operator. So let’s say we have: int var = 0; std::cout << var++ <<std::end; //...
69,861,914
69,862,042
Derived classes' attributes are empty
I am new to C++ and I am currently playing with inheritance. I am creating a base Polygon class that is inherited by Rectangle and Triangle classes respectively. From there I want to print out the area as defined in calcArea. However, the output of my derived class instances seem to be null. From what I understand the ...
The main problem is that you have variables in the sub classes shadowing the names in the base class - so you assign values to the variables in the base class, but you later print the values of the default initialized variables in the sub classes. You actually mostly need to remove code. I would rethink the name of the...
69,862,537
69,862,543
Why using if in this way is preventing it from running
so here the if inside the loop is it possible to write the if statement in an optimized way or should I just split the two conditions? #include <iostream> using namespace std; int main() { int grade, counter = 1, total = 0, average; while (counter <= 10) { cout << "Enter grade /100: "; cin...
if (grade < 0 && grade > 100) There is no number that is lower than 1 and bigger than 100, so that conditions will return false every time. If you want lower than 1 or bigger than 100, try: if (grade < 0 || grade > 100) Overall, your code should be: #include <iostream> // using namespace std; is bad practice, so don'...
69,862,779
69,862,809
where is the const-ness in this lambda capture argument introduced?
This code compiles correctly. #include <asio.hpp> #include <memory> #include <iostream> struct Message { int msg; }; // never mind global variables, just for the sake of making this a minimal example extern asio::ip::tcp::socket mysocket; void handler(std::shared_ptr<Message> pmsg, asio::error_code error, size_t nby...
psmg is captured by value, so it is read only inside closure. If you need it to be modifiable (because that is required by handler) you have to add mutable to the lambda: [pmsg](auto err, auto nbytes) mutable { handler(pmsg, err, nbytes); }); Live demo based on BoostAsio When pmsg is capture by value, the compiler is...
69,863,023
69,863,074
How to put numbers from txt file into vector in c++
I must say I'm completely new to C++. I got the following problem. I've got a text file which only has one 8 digits number Text-File: "01485052" I want to read the file and put all numbers into a vector, e.g. Vector v = ( 0, 1, 4, 8, 5, 0, 5, 2 ). Then write it into another text file. How do I implement it the best way...
You can use the following program for writing the number into another file and also into a vector: #include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> using namespace std; int main() { ifstream inputFile("input.txt"); std::string numberString; int individ...
69,863,051
69,863,357
what's wrong with my code? ( C++ if else with datastructures )
I was working on data structures with C++. Everything looks OK. This is a simple C++ file read. I think this code's output should be: 1 K 3 4 5 But I'm seeing: 1 2 3 4 5 How can I take data[4] in if? This is file.txt A(1#Jordan) A(2#Kyrie) A(3#Lebron) A(4#Harden) A(5#Doncic) This is my code #include <iostream> #incl...
there is a small error in how you compare a char to an int; the correct comparison is using '2': #include <iostream> #include <fstream> #include <string> using namespace std; int main(){ fstream file; file.open("file.txt", ios::in); if(file.is_open()){ while(!file.eof()) { char data[20]; f...
69,863,335
69,863,507
Reading a file in c++ and comparing between lines
Assuming a file.txt contains random files names as follows: a.cpp b.txt c.java d.cpp ... The idea is I want to sperate the file extension from the the file name as substring, and then compare between extensions to look for duplicates. Here is my code: #include<iostream> #include<fstream> #include<string> using namespa...
You can use the following program to print the count corresponding to each extension in the input file. The program uses std::map to keep track of the count. #include <iostream> #include <map> #include <fstream> int main() { std::ifstream inputFile("input.txt"); std::map<std::string, int> countExtOcc...
69,863,494
69,863,689
How to return an pointer to an item in the linear list
i have funcion that search a key in the linear list, but i have error when i want return pointer on an element. struct Item { datatype key; Item* next; Item* prev; }; int List::search(int x) { Item* temp = head; if (head == NULL) { cout << "Empty List" << endl; } while (temp != N...
How to return an pointer to an item in the linear list It is evident that for starters you need to change the return type of the function from int to Item *. Item * List::search( int x ); And within function you need to return indeed a pointer instead of the pointed item. The function should not output any message. ...
69,863,533
69,896,899
How to resize TextureArray in directx 11
I'm using a Texture2DArray to store the shadow maps of my directional lights. When a new directional light is added I want to resize the texture array to be able to hold the new shadow map. How can I achieve this? I need this, because it's very convenient to pass texture array to my shader and just index the correct te...
Recreating resource every frame is certainly wasteful, so creating a texture array and copy is definitely not very efficient. If your light count doesn't really change on a per scene basis, you can still totally create a new resource at the beginning of the scene (during load). In case you want it fully dynamic, you wi...
69,863,585
69,863,753
Printing the values from vector
I know the reason why this is happening but don't know how to solve this as I am new to STL. I am taking the inputs from the user and representing the weighted graph using vectors. I declared a vector pair<int,int> to store the value of the edge and the weight. #include<iostream> #include<vector> using namespace std; i...
j is a pair of int in order to access the first/second int you have to use j.first/ j.second for(pair<int,int> j:adj[i]) { cout<<i<<"->" << j.second <<endl; }
69,863,605
69,864,339
C++ different using declarations for different concepts
Let's say, I have my List<T> class. I have a lot of functions where I have to pass a single object of my T type. For instance void add(const T& item) { ... } and it makes sense if T is some class or a struct. However, if T is a byte or integer, it's pointless or even wrong to pas it via reference, since memory poi...
It sounds like what you need is conditional_t: #include <type_traits> template<class T> class List { using argType = std::conditional_t<(sizeof(T) > 8), const T&, T>; void add(argType item) { } };
69,863,700
69,863,872
Vector of vectors memory layout
A std::vector<T> has the property of storing its elements continuously in memory. But what about a std::vector<std::vector<T>>? The elements within an individual std::vector<T> are continuous, but are the vectors themselves continuous in memory (that is, the whole data kept in the outer vector would be one memory block...
A std::vector<T> internally stores a pointer to dynamically allocated memory. So while the elements of a single std::vector<T> will be continuous in memory there is no relationship to any pointers that those elements store themselves. Therefore a std::vector<std::vector<T>> will not have the elements of the "inner vect...
69,863,903
69,864,190
How to fix Debug Error from Microsoft Visual C++ Runtime library when dealing with threads?
I'm writing a program that will detect a key press and do something (in this case, show a message box). It all works fine, except when I try to exit the program, it shows a popup like this error window: Now, this window doesn't mess up anything in my program, so I could leave it there, but it is annoying. Here's a Min...
When the events loop ends, all of wWinMain's local variables are destroyed. One of them is td as your thread. When std::thread is destroyed while it is in joinable state, std::terminate() is called: std::terminate is called by the C++ runtime when the program cannot continue for any of the following reasons: a joinab...
69,864,187
69,865,621
C++ choose method based argument's dynamic type
Question Imagine I have some simulator library, that takes from me some objects (aka event handlers) and generates events for these objects by calling their handle_event(Event) method. The library provides me with the following classes: class Event {}; // Base class for all events // All event classes are derived from ...
Based on the requirements in the question and things discussed in the comments to @ypnos answer, I believe that you want or need to implement the visitor pattern here. One possible implementation would look like this (based on the Wikipedia article about Visitor Pattern: https://en.wikipedia.org/wiki/Visitor_pattern#C+...
69,864,408
69,865,077
What datatype would is expected for the arrays in c++?
I've been trying to assign a datatype to the three-dimensional arrays, e.g., double, but keep getting the error error: request for member 'size' in 'msd_x', which is of non-class type 'const sample_type' {aka 'const long unsigned int'} -> size_t N = msd_x...
I'm guessing here based on the many questions leading up to this. It is pretty obvious that you do not want sample type to be a scalar, but a 2-dimensional array. I will sketch a generic short-cut that would allow you to write mean_square_displacement::operator() to accept those, potentially even without knowing the co...
69,864,471
69,888,932
SFML no sound playing with soundbuffers stored in ResourceHolder
i'm currently working on a small game with sfml. For resource loading and holding i'm using the ResourceHolder described in the SFML Game Development Book: SFML ResourceHolder Basically the resources are stored as unique_ptr in a map. Inside a SoundManager class i'm loading different sounds to this ResourceHolder. This...
I was able to fix this issue with some enter link description here in the sfml-dev forum.
69,864,580
69,864,963
Quick method for search a value in a (sorted) circular data structure
I'm looking for an algorithm similar to binary search but which works with data structures that are circular in nature, like a circular buffer for example. I'm working on a problem which is quite complicated, but I's able to strip it down, so it's easier to describe (and, I hope, easier to find a solution). Let's say w...
If I understand correctly, you have an array with random access (if only sequential is allowed, the problem is trivial; that "window" concept does not seem relevant), holding a sequence of positive then negative numbers with a zero in between, but this sequence is rotated arbitrarily. (Seeing the array as a ring buffer...
69,864,700
69,864,788
In place construction of a pair of nonmovable, non copyable in a std::vector
Assume a following non copyable and non movable struct X with no default constructor and with no single argument constructor: struct X { X(int x, int y) { } X(const X&) = delete; X(X&&) = delete; }; and a vector std::vector<pair<X,X>> v. For inserting into v one could use emplace_back if X was constructibl...
std::vector is subject to reallocation once the size reach the capacity. when reallocating the elements into a new memory segment std::vector has to copy/move the values from the old segment and this is made by calling copy/move constructors. if you don't need that the elements are sequential in memory you can use std:...
69,864,834
69,864,912
How to std::copy between std::vectors<T> when T has const memers?
My main goal is to combine std::vector with ompenMP to make some parallel computations. I want to go with Z boson's answer where each thread works on its own copy of vector and at the end, we std::copy from all private vectors to the global one. Consider this example: #include<iostream> #include <vector> const int N = ...
Instead of calling resize and then copy-assigning your elements, you can reserve and then copy-initialize them: std::vector<foo> tree; tree.reserve(N); for (int i = 0; i < N; i += 2) { ... std::copy(vec_private.begin(), vec_private.end(), std::back_inserter(tree)); } This won't work if the goal is to have eac...
69,864,883
69,865,376
How can I use 2d vector as class member in private for create a game-board?
#include <iostream> #include <vector> using namespace std; class board{ public: /* vector<vector<int>>getmyvector(){ return vect; } board(vector<vector<int>>vect2){ vect=vect2; }*/ private: vector<...
You can use the below given program as a starting point(reference). The class board has a private data member named vect and public member functions called getVector, setVector and display. #include <iostream> #include <vector> class board{ public: //create getter std::vector<std::vector<int>> getVecto...
69,864,982
69,865,039
How to instantiate a class from the stack with different constructors?
I need to create a class instance from the stack, but depending on a variable I need to call it with different constructors class A { public: A(std::string str); A(int value) }; void main(void) { bool condition = true; A class_a {condtion ? "123" : 456}; } But I can't get it to compi...
The ternary operator can't return different types for true and false. You could solve it like this: A class_a = condition ? A("123") : A(456); Other fixes: #include <string> class A { public: A(std::string str) {} // the function must have an implementation A(int value) {} // the function must have ...
69,865,183
69,865,504
Get address of object cast to arithmetic type at compile time
I'm trying to implement x86 page tables/page directories in C++ and I would like to be able to construct these at compile time. In order to do this I need to be able to obtain the address of static constexpr page table objects at compile time, cast to an arithmetic type, such that I can use them to construct static con...
At compile-time, you're not generally allowed to do low-level chicanery like accessing the numerical value of an address. Even C++20's bit_cast is explicitly not constexpr if the source object is (or contains) a pointer. This is important because the address of things at runtime is not the same as their compile-time ad...
69,865,908
69,866,046
The c++ standard documentation says a program shall not call the main function, but I did
It explicitly says in the c++ standard documentation that a program may not call main. Yet I wrote a program that calls main and works perfectly fine, why is that? The code: #include<iostream> static int counter = 0; int main(){ counter++; std::cout << counter << " It works" << std::endl; while(coun...
basic.start.main/3: The function main shall not be used within a program. Violating this rule makes your program have undefined behavior - which means that the program can do pretty much anything. It may even do what you wanted it to do or appear to do what you wanted but have devastating side effects, so avoid having ...
69,866,102
69,866,160
How to avoid copy when i want to move data from stack to vector?
I have a very-frequently used operation, which need to move data from stack into vector. let me write a demo code: void handle(const std::vector<std::vector<std::pair<size_t, double>>> & v) { // this is my handle data function } int main() { std::stack<std::vector<std::pair<size_t, double>>> data; // this is my da...
This, your code, will create a copy of the vector. const auto & v = data.top(); params[cnt] = v; This will avert the copy, by moving the vector out of data. auto & v = data.top(); params[cnt] = std::move(v); Both operations are described, as forms (1) and (2), in cpprefernce.
69,866,267
69,866,419
Downloading files within a QCoreApplication
I work in a team to develop a QT Application with c++. Among other things, the app needs to download files from the internet. Here is the code I wrote to download files: int main(int argc, char *argv[]){ QCoreApplication app(argc, argv); QNetworkAccessManager man; std::string urlc = "https://upl...
The difference is that QNetworkAccessManager has a greater scope in the first case, as opposed to the second case, which is only a local variable, so it will be destroyed at the attempt. One way to solve is to create a class that handles all the logic: #include <QCoreApplication> #include <QFile> #include <QNetworkAcce...
69,866,617
69,866,683
Printing Value From Array in C++
I want to write a method in C++ which creates an array of monotonically increasing values. It has the inputs of int begin, int end, int interval. In this example; method should return the array of [0,1,2,3,4,5,6,7,8,9,10]. When I print the results it should print out the first two indexes and get 0 and 1. However, when...
try this. also add deletion of the newResult #include <iostream> using namespace std; int* getIntervalArray(int begin, int end, int interval){ int len = (end - begin) / interval + 1; int* result = new int[len]; int lastValue = begin; for (int i = 0; i <= len - 1; i++) { result[i] = lastValue;...
69,867,071
69,867,157
How to save data in file I/O in c++
i was trying to create login and registration syste. The registration work perfectly well until i stop the app and run it again so that i can login(it delete everything in the file). How can I make my file save even when I run again my app bellow is attached my code #include <iostream> #include <fstream> using namespa...
It is because whenever the output file is opened it clears the contents of it. You need to specify the option to append to the file in order to prevent that: fout.open("userDB.txt",std::ios_base::app);
69,867,221
69,868,066
Solving a C2039 error and a C3861 error using std::minmax_element
I'm newer to C++. I've written the following line in a test function inside a standard VS2019 test project: auto minAndMaxYards = std::minmax_element(simResults.begin(), simResults.end()); It yields both C2039 and C3861 errors for the minmax_element function even though intellisense recognizes it as a member of std, a...
Move #include "pch.h" to the top of the file. When using precompiled headers, the compiler ignores everything above this line. In your example, that would be #include <algorithm>, that's why std::minmax_element is not found.
69,867,376
69,867,492
Why does calling a function on seperate lines change the result in c++?
It seems that for some reason when I try to call two functions on the same line, the first function receives an nullptr from ".get()" as the first argument getSomePtr(someUniquePtr.get(), someArray)->moveUniquePtr(std::move(someUniquePtr)); But when separating these functions in to two separate lines, everything seems...
When evaluating an expression, function arguments are evaluated before the function that takes those arguments is called. However, outside that rule, the compiler gets to choose the order of evaluation. It looks like, in your first case, it chose to evaluate moveUniquePtr before evaluating someUniquePointer.get(). Be...
69,867,527
69,867,654
Can void loops run independently?
Basically, I have an Arduino Uno R3 hooked up to a 16x2 LCD screen and I want to make 3 different texts appear in the span of 16 seconds on line 0, and on line 1 I would like to add a seconds counter. When starting it the text portion works just fine but the seconds counter only appears after the 16 seconds when all 3 ...
Arduinos are single core controllers, so you are not able to run multiple loops in parallel without additional tasking features. What you most propably are looking for is called the Superloop. This is basically an endless loop, containing all tasks of your system. Tasks are then executed if a timing condition matches. ...
69,867,860
69,867,913
Forging multiple name lists from a text file into one
I need to get a list of names from a txt file, and then sort them in alphabetical order. But let's just focus first on getting the list itself.. This is the input txt file (the format is given by the exercise) (comments are explanation given by the exercise, they're not actually there) 3 // the number of total name gro...
You're reading the 6 as part of the names, your innermost loop should be: for(int j = 0; j < studNum; j++) and not for(int j = 0; j <= studNum; j++) Also, you never initialize the contents of the students array, so strcat will try to append the name to a string that possibly contains anything. You should zero out the...
69,867,979
69,868,032
Checking if a string contains a substring C++
I'm trying to make a program that checks if a string contains a substring of another string, but it's not working. Here is my code: #include <iostream> #include <algorithm> using namespace std; //Struct to store information struct strings { char string1[20], string2[20]; } strings; //Function to check if the str...
Wouldn't it be easier for strings to have two std::string instead of two char[20]? Then you would be able to say this with no problem: if (strings.string1.find(strings.string2) != std::string::npos) { std::cout << "found!" << '\n'; } char is not a class like std::string, it doesn't have any member functions. This ...
69,868,100
69,868,255
Why would you ever use heap allocation for objects you will reference through an std::vector?
I'm going through some code from this article about ECS-systems in game programming and trying to understand it, and something I'm seeing a lot is using heap memory in places where it seems like there is no benefit in doing so. Take this as an example: class ECS { public: void someFunction() { archetyp...
The obbious reason would be that you don't want the data items to be moved/copied when the vector grows, There may be several reasons for that, one is that the types are expensive (or even impossible) to move/copy, another is that you don't want pointers to the individual archetypes to be invalidated by changes to the ...
69,868,397
69,868,458
Vector Iterators Incompatible: proper way to iterate over two vectors?
One of my teachers has tasked us with creating a class that can iterate over two different vectors to make them appear as though they are contiguous from the pov of the caller. One of the requirements is that the vectors mustn't be copied. From what I understand, iterators from two different vectors cannot be compared ...
The way to do this is to hold internally two iterators. One to vec1, the other to vec2. First use the first one, then after the first one reaches the end of vec2 switch to the other one. Some snippets to see what I mean: itnerator& operator++() { if (it1 != vec1.end()) ++it1; else ++it2; return *th...
69,868,761
69,868,960
Should i use pointers or references?
I'm having problems figuring out if i should use pointers or references in certain methods I have a method called issueOrders(Orders* order) which takes a reference to an Orders object This method should add the pointer to order to a vector containing pointers to orders void Player::issueOrder(Orders* order) { orde...
As @UnholySheep pointed out, your getter returns a copy of the ordersList vector. What you want is a reference (or a pointer), so that your push_backs affect the vector. So you want to change its declaration to this: vector<Orders*>& getOrdersList(); And change its definition accordingly. Whether or not you should sto...
69,868,833
69,868,995
Cython: How to export C++ class to .hpp header instead of C .h header
This works fine in .pxd file: cdef public: struct foo: float bar But this doesn't work: cdef public: class foo: float bar # Syntax error in simple statement list This works but Cython is still making struct instead of class and the resulting file is .h file instead of .hpp (or .hh) file: cdef ...
I've figured out how to define C++ class (not the Python extension type 'class') in Cython only; it is still transpiled to .h file as struct but with methods inside: # Declaration cdef public: cppclass foo: float bar foo() # Constructor method() # Sample method # Implementation cdef cppclas...
69,868,985
69,869,287
c++ fstream getline function adds \r to the line size
When I run my code on Clion I dont get this error. But when i run my code on my school's dev server, I realize every line size except the last line in my file below has a size line.size()+1. This is my file 6 5 8 2 5 6 7 5 4 7 3 2 1 2 5 3 4 7 5 6 5 8 7 2 3 6 4 3 1 1 2 2 7 8 2 1 6 2 1 1 2 2 4 4 0 5 3 2 2 It reads first...
The problem was caused by the text file not having UNIX-style line endings ("\n"), but instead having Windows-style line endings ("\r\n"). On Windows, when opening a file in text mode (without ios::binary), the "\r\n" line endings are automatically converted to "\n" line endings. On Linux, this conversion is not necess...
69,869,100
69,869,236
Is it possible for a C++ iterator to have gaps and not be linear?
I wrote a C++ iterator to go over an std::string which is UTF-8. The idea is for the iterator to return char32_t characters instead of bytes. The iterator can be used to go forward or backward. I can also rewind and I suppose the equivalent of rbegin(). Since a character can span multiple bytes, my position within the ...
Many algorithms in C++ work equally well with plain pointers in addition to iterators. std::copy will work with plain pointers, just fine. std::find_if will be happy too. And so on. By a fortunate coincidence std::copy invokes the ++ operator on the pointers you feed to it. Well, guess what? Passing a bunch int *s to s...
69,869,356
70,051,285
Makefile objects in different folders with wildcard & headers (modular compile)?
UPDATE#04: Got everything compiling. Will keep the answer concise so here are some intermediary steps. Basically the Rules only partially worked because the objects were being made in their own folder still. After creating new local object Rules it compiled. However since they were now in their own directory the modula...
Here is the working pattern for wildcard & modular compiles with multiple targets. NOTE: You will have to remove header includes or conflicting %.o: %o.c Rules needed for same folder objects. Otherwise it will cause lots of weird missing target errors that change when you alter the Rule order (which just wastes your ti...
69,869,368
69,869,381
I cannot pass arguments to my class in c++
I’m trying to pass an argument to my class but it’s not working the #includes #include <iostream> #include <vector> #include <algorithm> #include <string> #ifdef _WIN32 #include <Windows.h> #else #include <unistd.h> #endif the class Name and age are vectors Don’t mind the function called oldP class user{ ...
Your constructor takes arguments of type vector<string> and vector<int> but you are trying to pass in values of type string and int. Since there is no implicit conversion from a given type T to a type vector<T>, you'll need to rectify that mismatch -- either change the types that constructor accepts, or change the typ...
69,869,523
69,869,560
[C++]Why Iterating over a std::string using std::stringstream gives an exception character?
I'm trying to implement a simple format function that fills in the corresponding content based on the given format character. I use std::stringstream to convert the given format string into a stream, and then take out the characters one by one. Then, based on the individual characters, fill in the relevant content into...
Let's say that the last character in the stream has just been processed. There's nothing left in the stream. while (s_fmt.good()) { This is perfectly fine. After all, why wouldn't it be? Everything worked swimmingly well, up until now. The entire string has been read. Everything is still good(). The while loop continu...
69,869,577
69,870,505
How to dump my class(with stl container) out, make it fast to load next time?
I have a large container class to read file and save some data, it looks like: class MyData { public: void Load(const std::vector<string>& file_paths) { // this is a slow funuction, need to read a lot of files. for (const auto & f : file_paths) { // read file, and save the data in to stl containers ...
Sure you can. For vector<double> you can simply use ofstream::write(a.data(), a.size()). For things like maps you need to do some kind of serialization because their internal representation is more complex. You could use http://www.boost.org/libs/serialization/ for a somewhat generic solution or you could write the ...
69,869,648
69,869,680
The last digit of entered value is always 7 or 5 when entering a big number
I'm trying to get the last digit of entered value in C++. Why the output is always 7 or 5 when I enter a big number e.g. 645177858745? #include <iostream> using namespace std; int main() { int a; cout << "Enter a number: "; cin >> a; a = a % 10; cout << "Last Number is " << a; return 0; } Outp...
The largest value that an int (on most machines) can hold is 2147483647 You enter 8698184618951, which is bigger than 2147483647. Because an int can't hold 8698184618951, extraction will fail but a will now be the max value that it can hold. So a is now 2147483647. You should use a bigger type, like long long instead o...
69,869,830
69,869,886
Program won't display info in while loop
I am trying to teach myself C++ and I was working on a login system as a way to help better my understanding. I am facing an issue however, the program will not print out anything inside the while loop I made, there are no syntax errors showing when I try to run it and the program doesn't end, it just sits there until ...
#include <iostream> #include <list> int main() { //existing users lists std::list<std::string> Username = {""}; std::list<std::string> Password = {""}; //create account std::string newUsername; std::string newPassword; //login info std::string existingUser; std::string existingPass; //creating account input std::...
69,869,838
69,869,921
Convert from UTC date string to Unix timestamp and back
How to convert from string like “2021-11-15 12:10" in UTC to Unix timestamp? Then add two hours to timestamp (like timestamp += 60*60*2). Then convert resulting timestamp to string in the same format in UTC? Using <chrono>, <ctime>, or library, doesn’t really matter.
You could use the I/O manipulators std::get_time and std::put_time. Example: #include <ctime> #include <iomanip> #include <iostream> #include <sstream> int main() { std::istringstream in("2021-11-15 12:10"); // put the date in an istringstream std::tm t{}; t.tm_isdst = -1; // let std::mktime try to fi...
69,870,078
69,875,187
Visual Studio C++ has different comparison results for UINT16 and UINT32
I caught myself checking if the difference between two unsigned numbers was >= 0. I ran a test running Visual Studio 2022 Preview with the following code. In both cases the answer was true. That seems right to me as how could an unsigned number be considered negative? However, when I changed all the types from UINT32 t...
The issue arises because, when a and b are UINT16 or UINT8 types, they have ranks less than that of the int type, so, by the "usual arithmetic conversion" rules, they are promoted to int before the a - b operation is performed, and the result of that operation is also of int type. From this draft C++17 Standard (boldin...
69,870,289
69,870,347
Am replacing the first occurrence of a string, how can I replace all occurrences?
I have already bulid the basic structure by using the loop + replace,In C++, the str.replace is only to replace single string, however, in some cases, we need to replace all the same string, My code can compile successfully and can output to the screen, but it seems that it does not replace successfully. Thanks in adva...
You need to save pos and use it for the following find operations but you currently initialize it to 0 every iteration in the while loop. You could replace the while while loop with this for example: for(std::string::size_type pos = 0; (pos = words.find("C", pos)) != std::string::npos; // start find at pos pos ...
69,870,439
69,870,580
Overloaded function and multiple conversion operators ambiguity in C++, compilers disagree
In the following program struct S provides two conversion operators: in double and in long long int. Then an object of type S is passed to a function f, overloaded for float and double: struct S { operator double() { return 3; } operator long long int() { return 4; } }; void f( double ) {} void f( float ) {} ...
GCC and Clang are correct. The implicit conversion sequences (user-defined conversion sequences) are indistinguishable. [over.ics.rank]/3: (emphasis mine) Two implicit conversion sequences of the same form are indistinguishable conversion sequences unless one of the following rules applies: ... (3.3) User-defined conv...
69,870,606
69,871,251
`bool n;` `n++;` is invalid but `n=n+1;` or `n=n+3` such things works what's the significance of this?
Code C++17 #include <iostream> int main() { bool n=-1; n++; // Not compiles n=n+3; // This compiles return 0; } Output ISO C++17 does not allow incrementing expression of type bool So I am not understanding the significance of allowing addition but not increment.
As you can see in section 5.3.2 of standard draft N4296, this capability has been deprecated The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated) Please note that the expression n=n+3; is not a unary statement, and it's not something that we could call deprecated. If...
69,870,746
69,871,293
arduino on / off NON momentary switch implementation assistance
I am new to programming and Arduino. Board - ESP8266 Nodemcu pinout as below, What I am trying to achieve is send a command based LOW/HIGH value from pin 0. A two leg switch's one leg is connected to D3 (GPIO0 and in program 0) and other to ground. The code I am trying is below, #include<BitsAndDroidsFlightConnector.h...
If you want to see message only once you need to write youre code in setup() section. All code in loop() section is repeated in loop. Replace you code with this: #include<BitsAndDroidsFlightConnector.h> BitsAndDroidsFlightConnector connector = BitsAndDroidsFlightConnector(); const byte exampleButtonA = 0; int example...
69,870,759
69,870,793
Creating a 2D Array using dynamic memory allocation in C++
I am trying to implement a 2D array using dynamic memory allocation. Here is my code: #include <iostream> using namespace std; int main() { int r, c; cin >> r >> c; int** p = new int*[r]; for (int i = 0; i < r; i++) { p[i] = new int[c]; //this line here is the marked line } for (int i = 0; i < r; i++)...
In general the program has undefined behavior. In this for loop for (int i = 0; i < r; i++) { p[i] = new int[i + 1]; //this line here is the marked line } in each "row" of the array you allocated i + 1 elements. But in the next for loop (and in subsequent loops) for (int i = 0; i < r; i++) { for (int j = ...
69,870,809
69,870,855
the correct use for auto &i range?
#include <iostream> #include <vector> class UserData { std::string status = "Active"; public: std::string first_name; std::string last_name; std::string get_status() //no colon { return status; } }; int main() { UserData user1; user1.first_name = "LaLaLa"; user1.last_name = "G...
The compiler tells you already what is missing. Your class does not have an << operator. So, please add it and all problems are solved. Example: #include <iostream> #include <vector> class UserData { std::string status = "Active"; public: std::string first_name; std::string last_name; std::string get_s...
69,871,195
69,871,372
C++ conditional execution depending on the type
I have a template function that should execute different code, depends on the type. The simplified function looks like this: template<typename T> std::string test(T value) { std::string v; if(std::is_arithmetic<T>()) { v = std::to_string(value); } else { v = std::string(value); ...
You can apply overloading with SFINAE. E.g. // for arithmetic types template<typename T> typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type test(T value) { std::string v; v = std::to_string(value); return v; } // for non-arithmetic types template<typename T> typename std::enable_if<!s...
69,871,552
69,871,645
strange behavior of C++ downcasting on object
i ran the code below to assign parent portion of objet to child object. but as described inline, c style downcast behaves something unexpected. what happen there? please refer to the comment below. struct A { public: int i{}; A() { std::cout<<"A constructor called\r\n"; } ~A() { std::cou...
magic is here: (A)b = a; what happend is: call A's copy constructor and create a new [class A object]. it's a temporary object, and it's destoryed after this statement. so print [A destructor called <-- please note here] call A's operator= on the temporary object. it's only effect the temporary object instead of origi...
69,871,605
69,871,701
how to understand const and pointer in C++ expression below?
I am reading application code developed in the IBM RSARTE C++ version. Here is a piece of C++ code: const char * const * av = RTMain::argStrings(); How to understand the left-hand side syntax when there are two const and two *?
const char * const * av = RTMain::argStrings(); is the same as char const * const * av = RTMain::argStrings(); const applies to what's left of const. So, av is a non-const pointer to a const* to const char. The returned pointer, av, is non-const and can be changed. The pointer av is pointing at is const and can not ...
69,871,723
69,871,835
C++ read data types string int and double using Vector Pair
The problem is that i have to read a file that includes: type count price bread 10 1.2 butter 6 3.5 bread 5 1.3 oil 20 3.3 butter 2 3.1 bread 3 1.1 I have to use Vector Pair to read the file and to multiply the count and price and the outp...
If you only want to use std::pair and std::vector then you could use the following program as a starting point(reference): Version 1: Product names will be repeated #include <iostream> #include <fstream> #include <sstream> #include <vector> int main() { std::ifstream inputFile("input.txt"); //open the file std:...
69,872,293
69,872,369
Why I am having a weird mistake while trying to read a file from the end to the middle, using fin2.seekg(-2 * sizeof(int), ios::cur); ? no string
Thanks for paying attention to my question. Recently, I've started working with c++ files and now I'm having a couple of questions about reading the file from the end to the middle. My task is to read my two files from the end to the middle and from the beginning to the middle with no arrays and string library used. Af...
Instead of fin2.seekg(-2 * sizeof(int), ios::cur); do fin2.seekg(-2 * static_cast<ifstream::off_type>(sizeof(int)), ios::cur); where off_type is the offset type of the stream. Otherwise, -2 will be cast to size_t, which is the type of sizeof, and which is unsigned - so the negative value -2 will become a very large v...
69,872,372
69,872,429
Easiest way to combine 3 std::vector into a temporary single std::vector?
I have seen this discussion (Concatenating two std::vectors) but it concerns combining (as in moving) two std::vector arrays. I have three std::vectors and I am using C++17: m_mapHist[m_eHistAssign][strName] m_mapScheduleHist[m_eHistAssign][strName] m_mapScheduleFutureHist[m_eHistAssign][strName] Each vector is of t...
You may use boost::join. Example: std::vector<COleDateTime> v1; std::vector<COleDateTime> v2; std::vector<COleDateTime> v3; std::vector<COleDateTime> result; result = boost::join(boost::join(v1, v2), v3); Since c++17 the standard also have a std::merge util function: std::vector<COleDateTime> v1; std::vector<COleDate...
69,872,375
69,872,570
C++ STL stack vs forward_list
I have a use case where I need to store some amount of uint16_t variables in no particular order (although the actual type of variables is not relevant). I have decided to turn to the STL to look for a container that best suits my needs. The objects in the container may get taken out of it to be used and put back into ...
TLDR: If you only need to add / remove the last element, use vector or stack. This is the fastest option and has the lowest overhead. Long version: Look up comparisons between linked list and dynamic arrays, for example here: vector vs. list in STL Most of the discussion will be about std::list but the same principles ...
69,872,689
69,872,763
I want to sort an array of structures using templatized qsort
I have an array containing pointers to objects. Each object has a data member called name of type string. I want to sort it using the templatized qsort function. Note again that each element in the array is a pointer to an object. However, I get the error: error C2227: left of '->name' must point to class/struct/union/...
name is a c string. Is there any reason why you do not use c++ strings from stdlib ? You won't be able to compile a code with a template ? Or std::sort ? Anyway, the problem is that when you call the template, you define the type as a pointer. You end up with a pointer to pointer, which has no field "name".
69,872,960
69,872,984
Why is my method for finding all divisors for two numbers isn't working
So I made a while loop for finding all divisors for given numbers and it's the following int a,b; int temp =0; cout << "Enter the first number : "; cin >> a; cout << "Enter the second number : "; cin >> b; int smallestNum = a<b?a:b; while(true) { temp++; if(a%temp == 0 && b%temp == 0) cout << temp ...
for loop will iterate as long as condition is true, your condition is i == temp which is (in general) false, you should change it to i != temp