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 |
|---|---|---|---|---|
66,963,974 | 66,964,091 | How to make the shared value behave consistently without mutex? | I have the following code. I do not understand why the reader sees inconsistent variable value.
uint64_t get_counter() {
static uint64_t counter = 0;
static std::mutex m;
std::unique_lock l(m);
return ++counter;
}
auto main() -> int {
// uint64_t shared = 0;
std::atomic<uint64_t> shared = 0;
... | Seems to me like the following sequence is possible:
Writer1: get_counter() -> 2
Writer2: get_counter() -> 3
Writer2: shared = 3
Reader: local = shared (3)
Writer1: shared = 2
Reader: if (local > shared) // 3 > 2
Since your lock doesn't cover the generation + assignment you have a "race condition" on the write t... |
66,964,005 | 66,964,394 | How to convert vector<pair<string, T>> to vector<pair<string,string>> | I have a method that requires me to return a vector<pair<string, string>>. However, the input I have is of vector <pair<string, T>>. This is part of a bigger question to return the number of edges in a graph. The relevant code is down below where T is an integer type.
map<string, string> all_vertices;
map<string, map<s... | I suggest that you skip the intermediate step of creating e and go directly to e_string. Also, make get_edges() const since you're not changing *this.
Use std::to_string to convert the integer T to a std::string.
The real problem is however that your code tries to add only one vertex + the weight for each edge.
In your... |
66,964,229 | 66,964,445 | Unclear ANSI CUB/CUF behaviour | While studying the ANSI control sequences I came across unclear behaviour.
I tried to make "matrix" effect in terminal, which
changes one random digit per loop iteration in a row of n 0/1 digits:
#include <iostream>
#include <chrono>
#include <thread>
const int n = 5; // row length
const int pause = 50; // millisecond... | It seems that \x1b[0C moves cursor to the right, at least on my terminal, (dunno if that is specified/required behavior).
$ printf "a\x1b[0Cb\n"
a b
$ printf "a\x1b[1Cb\n"
a b
Check if offset - 1 is not zero.
if (offset - 1) {
cout << "\x1b[" << offset - 1 << "C";
}
|
66,964,958 | 66,965,097 | Is std::map creating a new non const copy of object from its const reference | Consider the following code .
#include <iostream>
#include <map>
class A{
public:
int m_id;
int m_x;
int m_y;
A() = default;
A(int i, int j, int k) : m_id(i), m_x(j), m_y(k){}
};
void add(const A& a, std::map<int,A>& m){
m[a.m_id] = a;
}
void modify(std::map<int,A>& m){
for(auto& x : m)... | Yes, a new object will be constructed as the element of std::map. To be precise, in m[a.m_id] = a;, if the key (i.e. a.m_id) does not already exist, a value-initialized A will be constructed as the new element of m firstly, then m[a.m_id] returns the reference to value of the new element; which is copy-assigned from a ... |
66,965,144 | 67,001,223 | VS2017 property sheet replacement issue | Some time ago I wrote a point cloud drop sampling code, directly call someone else's library "Library111" and property sheet.However, since the property sheet was not working well, the library was deleted and a new library named "Library_original" was copied.
During this period of time, the code of point cloud drop sam... | According to the error message, you should check if the path is right.
If the file from D:\Library111\pcldebug_vs2017.props exists and there is no spelling errors under the path.
You should use this under the vcxproj file:
<Import Project="D:\Library111\pcldebug_vs2017.props"/>
After that, close VS, restart your proje... |
66,965,470 | 66,967,571 | Merge/concatenate unknown amount of byte arrays | I can merge/combine/concatenate two arrays with the following function, but how could I rework it to support unknown amount of arrays. In other words a variadic function Args...?
char* concat(char* a, size_t a_size,
char* b, size_t b_size) {
char* c = realloc(a, a_size + b_size);
memcpy(c + a_size,... | Using spans and vectors, you could write this as:
std::vector<std::byte> Concat(std::span<std::byte> a)
{
return std::vector<std::byte>(a.data(), a.data() + a.size());
}
template<typename... Args>
std::vector<std::byte> Concat(std::span<std::byte> a, Args... args)
{
auto vec = std::vector<std::byte>(a.data(), a.... |
66,965,529 | 66,971,509 | Is 11 a valid output under ISO c++ for x86_64,arm or other arch? | This question is based on Can't relaxed atomic fetch_add reorder with later loads on x86, like store can?
I agree with answer given.
On x86 00 will never occur because a.fetch_add has a lock prefix/full barrier and loads can't reorder above fetch_add but on other architectures like arm/mips it can print 00. I have a tw... | Yes, ISO C++ allows this; as Daniel pointed out, one easy way is to put some slow stuff after the RMWs, before the loads, so they don't execute until both threads have had a chance to increment. This should be obvious because it doesn't require any run-time reordering to happen, just a simple interleaving of program-o... |
66,965,680 | 66,965,882 | Count the number of occurences of each number in a random array | I am writing a code that makes an array of 100 integers filled with random integers. Then it will count the occurrence of each integer and print them out as shown:
1 occurs 1 time
2 occurs 15 times
3 occurs 9 times
etc...
The problem with my code is that I am getting weird counts. For example, 10's occurrence is 100 b... | If you look carefully at the output, you will notice that count never decreases.
This is because you declared it outside the loop and then only increment it.
(So the "count" of the largest number in the array will always be the size of the array.)
Move the counter inside the loop, into the context of the x that it's co... |
66,965,686 | 67,027,925 | Implement tree structure. Store nodes in vector and denote children with indices? Or store nodes on the heap and use pointers to the children? | I have to implement a tree structure in C++ (a trie to be exact). It's on the hot path and will presumably get very big (hard to give an expectation, maybe around 1mio nodes).
Therefore, I am currently thinking about how to implement the structure as efficiently as possible. I have two ideas in mind:
The first is rath... | The standard efficient C++ way of doing that is to write your data structure without worrying about how data are allocated, and use a dedicated allocator template parameter (like std::vector or std::map). This method helps to keep your code maintainable (thanks to separation of concerns) and be still quite efficient (t... |
66,965,805 | 66,965,952 | C++: passing the template callback method into the other method: cannot convert ‘<unresolved overloaded function type> to pointer | I have a container that stores the structures that contain the template callback.
At the same time callbacks signature does not contain template parameters.
When inserting into it, I get the error:
cannot convert ‘<unresolved overloaded function type>’ to ‘smb1_subdecoder::send_subflow_premature_end_msg_t’ {aka ‘void ... | You must qualify the name of a non-static member with the class name explicitly when constructing a pointer to member.
(emphasis mine)
If the operand is a qualified name of a non-static member, e.g.
&C::member, the result is a prvalue pointer to member function or
pointer to data member of type T in class C. Note tha... |
66,965,890 | 66,966,076 | C++ Why parameterised constructor works diffrent with char*? | I recently started to work with C++ classes and everything was fine until i wanted to create a class with 'char*' parameter.
I created a default constructor, a parameterised constructor, a copy constructor and a destructor.
Tested it on int* / float parameters and it worked.
Now i tried to switch to char* and ... it di... | As mentioned in comment, you should first read about The rule of three.
If a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three.
So you should define by yourself a copy-assignment operator. It can be implemented... |
66,965,898 | 67,173,814 | grpc/c++ Handshaker factory creation failed with TSI_INVALID_ARGUMENT | I am creating a static library out of my grpc c++ client and I am able to successfully call the API in the grpc static library using a test application.
But when I integrate the static library with a different service and call the API in the grpc static lib from that service, it fails with the error below
Handshaker fa... | The application that I was trying to integrate was using libssl 1.0.2 which doesn't support TLS1.3 but grpc 1.35 by default uses TLS1.3 and openssl 1.1.1. So built gRPC with gRPC_SSL_PROVIDER=package and it picked up libssl 1.0.2 and that fixed the issue. Hope this helps anyone.
|
66,965,949 | 66,966,595 | Is there a way to protect a smart pointer from being deallocated on one thread, when work is being done on another thread? | In our program, we have a class FooLogger which logs specific events (strings). We use the FooLogger as a unique_ptr.
We have two threads which use this unique_ptr instance:
Thread 1 logs the latest event to file in a while loop, first checking if the instance is not nullptr
Thread 2 deallocates the FooLogger unique_p... | The purpose of std::unique_ptr is to deallocate the instance once std::unique_ptr is out of scope. In your case, you have multiple threads each having access to the element and the owning thread might get eliminated prior to other users.
You either need to ensure that owner thread never gets deleted prior to the user t... |
66,966,248 | 66,966,384 | Win32 Window Doesn't Draw After minute or so | I am in a sticky situation.
I'm messing around with Bitmaps and windows.
I followed this tutorial: https://learn.microsoft.com/en-us/windows/win32/gdi/capturing-an-image
I am basically taking multiple pictures of my desktop and displaying them into a window.
It works great as intended but after like a minute or 2 the w... | I think you have spent all resources.
For example,
You create bitmap every cycle and don't release it.
You call SelectObject and don't return selected object to original state.
|
66,966,426 | 66,966,679 | Error defining an unnamed structure in c++ | I'm having a problem with my code, even my professor has no idea why this is the case.
He wants me to define the structure with using Persontype= struct{}; and not a normal definition of a structure. I don't understand why or what is the difference.
he also don't want us to include the .cpp file in main.
Normal definit... | My interpretation
using PersonType = struct { ..... }; on a top-level will generate a different anonymous type in each translation unit (.cpp file, for simplicity) and then give it a name of PersonType in each translation unit. It does not matter that this statement happens inside test.hpp, all #includes are handled by... |
66,966,635 | 66,967,359 | Is there a way to refer to a later defined struct (either by prototyping or else)? | I am trying to use struct for defining in a centralized way how xml nodes are defined that I want to read by my code.
This currently looks like this:
const struct sXmlRootDefinition
{
const char* name = "case";
const char* parents[1] = { "none" };
} sRootDefinition;
//------------------... | You can use a proper constructor, and maybe use the standard library for strings and dynamic arrays:
#include <vector>
#include <string>
struct XmlRootDefinition
{
std::string name = "case";
std::string parent = "none";
std::vector<std::string> children;
};
struct XmlCaseDefDefinition
{
XmlCaseDefDefi... |
66,966,832 | 66,967,033 | Histogram of arrays (C++) | I am writing a code that generates a random array length of 10 filled with random integers between 1 and 20 using a function to initialize it. Then it will print out a histogram of asterisks of the amount times the number is printed in the array.
Here is an example:
Element Value Histogram
0 12 ... | Your code is a c style program, which is error-prone, I have tried my best to achieve your requirement
#include <ctime>
#include <iomanip>
#include <iostream>
using namespace std;
void initialize(int arr[]);
const size_t kArrayNum = 10;
const size_t kMaxVal = 21;
int main() {
int arr[kArrayNum];
srand(time(null... |
66,966,835 | 66,967,173 | Can GNU Readline handle multiple streams? | I'm building a telnet application which uses GNU Readline to handle console input. Current implementation forks a new child for every new client connection - this assigns one readline instance for each child process.
Fork-type network servers are not the most efficient, so I'd like to use poll/epoll instead, but for th... | Readline is documented to read specifically from the terminal. It has no documented mechanism to maintain state for multiple inputs at the same time, and you're already on thin ice using it to read from a stream that is not, in fact, a terminal.
Moreover, the semantics of readline do not match a multiplex style servic... |
66,967,644 | 66,967,702 | makefile error lib/Scrt1.o undefined reference to `main' | I glanced tons of similar topic, but I couldn't recognize solution
I tried mine and many variations. Even below the simplest code compiling doesn't work. I think skipping little thing...
Could you help me?
# Make file for test.c file dependencies external C libraries
CC = g++
C = gcc
FLAGS = -Wextra -... | You forgot to link in test.o:
test: randomArray.o test.o
$(CC) $(FLAGS) $(INCLUDES) randomArray.o test.o -o test
Also note that test.o: randomArray.o is probably wrong. It says test.o depends on randomArray.o, which it doesn't. It depends on test.cpp.
test.o: test.cpp
$(CC) $(FLAGS) $(INCLUDES) -c test.cpp
... |
66,968,168 | 66,968,391 | In C++ can a derived class (with more parameters than it's Base class) use base class functions and overloaded operators? | Im new to c++ classes so this question may look stupid for some people, but i wonder if we can use base class functions in derived class, like we do with constructors?
As far as I know, constructors from base class can be used in derived class without copying the same lines of code again and again, just slightly modify... | Two problems.
The assignment operator always has to take exactly one argument. If you think about it, two arguments doesn't make sense, as there's always only one thing on the right hand side of the = sign:
child1 = child2; // child2 is passed into operator= for child1
Since a const parent& is in particular a const ch... |
66,968,292 | 66,969,037 | C++ socket programming bind function | Im learning socket progrmming in c++ and i don't understand why this function binds the socket to 'localhost'. For example, in python you have to specify the host like this:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 1234))
If I'm not wrong, this c ++ function is binding the socke... | Binding to "localhost" or INADDR_LOOPBACK binds to the loopback interface only. It will allow connecting locally using e.g. 127.0.0.1, but not from the network.
Binding to INADDR_ANY binds to all interfaces. It will allow connecting to this machine from another machine via the network using its network IP (e.g. 192.168... |
66,969,141 | 66,969,269 | Does casting to or from a double and a float preserve infinity and NaN? | When casting double infinity to float and vice versa, will it still be infinity? Is it the same with NaN?
| Converting any float to a double is guaranteed to preserve the value. Converting a double to float is guaranteed to preserve the value if the original value is representable as float.
If your system conforms to IEEE-754, then float is able to represent infinity and NaN. Otherwise, you can use <numeric_limits> to check ... |
66,969,288 | 66,974,981 | How to get size of nlohmann json object in memory? | How do I get the size of nlohmann object in memory in bytes?
The .size() operator gives the number of elements.
I have a lot of sub keys and elements.
What can I do to find it?
| Technically, you'd get this by using a custom allocator. The NLohmann JSON library supports custom allocators, which replace std::allocator. You can provide one that counts the various allocations. Note that the support is a bit flawed.
But as the comments suggest, you want a smaller representation. The working copy in... |
66,969,300 | 66,977,829 | Duplicated icons in CListViewCtrl | I know that the main problem comes from recursively calling FindFile(). With recursively calling this function, my i becomes 0. But I don't understand how I can fix this problem.
If possible, give advice on how to fix this bug without completely reworking all the functions below. Or provide a link where you can read ab... | You need to pass the value of i as a reference to FindFile so that when you call it recursively the value continues to increment.
void Finder::FindFile(CString szPath, int& i)
{
HIMAGELIST hSmall{};
CFindFile F;
CString S = szPath + TEXT("\\*.*");
// int i = 0; <-- not declared here, as it is now an arg... |
66,970,594 | 66,973,124 | What are the exact inter-thread reordering constraints on mutex.lock() and .unlock() in c++11 and up? | According to https://en.cppreference.com/w/cpp/atomic/memory_order mutex.lock() and mutex.unlock() are acquire and release operations. An acquire operation makes it impossible to reorder later instructions in front of it. And release operations make it impossible to reorder earlier instructions after it. This makes it ... | Almost a duplicate: How C++ Standard prevents deadlock in spinlock mutex with memory_order_acquire and memory_order_release? - that's using hand-rolled std::atomic spinlocks, but the same reasoning applies:
The compiler can't compile-time reorder mutex acquire and release in ways that could introduce a deadlock where t... |
66,970,750 | 66,970,880 | Making a function use std::span instead of the old way | I just learned that I could use VS 2019 with C++ 20 and I'm trying to make use of it. I'm trying to make the following function use std::span, because that way data_size and key_size would be redundant.
Everything is alright except *data and data++. What is it supposed to be?
int rc4(rc4_context* context, const std::ui... | First, the pair of parameters (const std::uint8_t* data, const std::size_t data_size) can be replaced by std::span<uint8_t>, not std::span<uint8_t*>.
Second, you don't need to bother incrementing data since you can rewrite this to be a range-based for loop:
for (uint8_t elem : data) {
// Adjust indices
i = (i +... |
66,972,564 | 66,972,953 | function template explicit specializatioin | I'm learning c++ template and i have a question.
#include <iostream>
#include <string>
using namespace std;
template <typename T>
size_t GetStringSize(const T& s) { return s.size(); }
template<>
size_t GetStringSize(const char* s) { return s.strlen(); }
template<typename T,typename... types>
size_t GetStringSize(c... | Problem #1: You are missing the include that declares strlen. Your compiler may allow this omission, but the next version may not!
#include <cstring>
Problem #2: You are misusing strlen syntax.
return strlen(s);
Problem #3: const char* cannot be a specialization of const T& because it is not a reference and is not... |
66,972,617 | 66,996,630 | Render SVG from server response | I am working on an application that requires a server request for an SVG that is representative of a particular product configuration. This is my first time dealing with SVG and I am hung up on decoding the server response in such a way where the image can be displayed with a QSvgRenderer. Something like this
QByteAr... | After a number of tests, I discovered the problem originated with the encoding. QSvgRenderer does not have the ability to decode the server response directly, which was causing renderSVG.load() to fail. I had to use QTextDocument's decoding function to decode the resposne in such a way where QSvgRenderer can read it.... |
66,973,024 | 66,973,439 | Migrating to unique_ptr from a dynamic array and failing to convert to std::span | I'm trying to encrypt and decrypt a file, basically exercising std::span and std::unique_ptr. The issues are commented in the code.
2nd parameter of rc4 is std::span but my parameters are vector<uint8_t> for the encryption and unique_ptr<uint8_t> for the decryption, which I'm unable to convert to.
*output++ = elem ^ s... | I recommend using std::vector<uint8_t> for result too, but here's how you can fix the code you've got. I've made it minimal in the answer to focus on the issues.
#include <cstdint>
#include <iostream>
#include <memory>
#include <span>
#include <vector>
// rc4's span should be over const uint8_t's:
void rc4(const std::... |
66,973,495 | 66,973,765 | show the most entered salary between 2 employees using class c++ | so I have to write this c++ program that gets 2 employees information (including name, personnel id, and salary) and after comparing them, it will show the employee's name with the most salary. instead of the easy way, I should use class to write this.
here is my code:
#include <iostream>
#include <conio.h>
using names... | This is your problem:
void most_sal(){
int max = 0;
if (emp_sal > max){
cout << emp_name;
}
}
max is a local variable set to zero. Each time you call it, it is reset to zero. So the compare (assuming the employee is going to be paid) is always true.
What you really need to do is compare e1.emp_... |
66,973,538 | 66,973,701 | Invoke function with each argument | I'd like to invoke a function with each argument passed as a parameter pack.
I have already written a simple template function:
template<class Function, class... Args>
auto for_each_arg(Function f, Args&&... args) {
(f(std::forward<Args>(args)), ...);
}
It works fine when I use it with a function taking only one p... | void bar(int a, int b) { }
for_each_arg(
[](auto&&tup){
return std::apply(bar, decltype(tup)(tup));
}
)(std::make_tuple(1, 2));
Here the caller bundles arguments into tuples, and we unpack them into the call. This makes the packaging of which arguments go where clear.
We can move the apply call into the forea... |
66,973,815 | 66,973,931 | Exception thrown: write access violation. prev_ptr was 0x4 | I am learning about linked lists, and I decided to try implementing linked lists in C++ on my own.
I made a Node class with attributes int val and Node* ptr.
Then I made a Linked_list class with the attribute first_node, and the constructor functions work.
The append() function 'appends' a node to the list (like in Pyt... | ptr = (*ptr).ptr;
prev_ptr = &((*ptr).ptr);
First you advance ptr to the next node. Then, you use ptr again forgetting that it has already been advanced: (*ptr).ptr now points two nodes forward, and we don't know if we can go that much far.
Perhaps you need to swap the assignments.
... |
66,975,444 | 66,976,102 | Does this multithreaded list processing code have enough synchronization? | I have this code in test.cpp:
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <thread>
static const int N_ITEMS = 11;
static const int N_WORKERS = 4;
int main(void)
{
int* const items = (int*)std::malloc(N_ITEMS * sizeof(*items));
for (int i = 0; i < N_ITEMS; ++i) {
... | Looks safe to me. Your i = place.fetch_add(1) allocates each array index exactly once, each one to one of the threads. So for any given array element, it's only touched by a single thread, and that's guaranteed to be safe for all types other than bit-fields of a struct1.
Footnote 1: Or elements of std::vector<bool> w... |
66,975,491 | 66,975,636 | How to use C++ 20 in g++ | I am trying to access std::popcount, but it seems like it's only there in C++ 20.
When I try compiling with g++ -std=c++20 main.cpp, it says g++: error: unrecognized command line option '-std=c++20'; did you mean '-std=c++03'
How do I tell g++ to use c++ 20?
I am using Ubuntu 18.04
| I would try updating gcc. C++ 20 was introduced in gcc version 8 which is pretty new.
|
66,975,674 | 66,975,888 | Concatenating struct in byte array | I want to concatenate two structs. The problem is that I cannot convert that struct to a std::span, because span's constructor doesn't support void*. I'm using the same concat function to concatenate std::vector<uint8_t> as well, so any changes made to that function, shouldn't affect it. If it's possible to convert the... | You can provide a way to reinterpret an address as a span:
auto to_span(address const& a) -> std::span<uint8_t const> {
return {(uint8_t const*)&a, sizeof(a)};
}
And then the rest of your stuff just works:
auto c = utils::concat(to_span(address), to_span(other_address));
This can be generalized to support trivial... |
66,975,907 | 66,976,519 | Template Specialization Based Upon is_pointer Trait | I am sure this has been answered before however, I am not sure what the correct terminology/wording of my question is.
Take the following example class:
class Fooable {
public:
int foo(int a);
};
I want to write a template class that can call the foo() method of any generic type regardless if it is a pointer type ... |
Is this a good place to use the std::is_pointer trait?
Not exactly, though a trait would help. std::is_pointer determines whether a type is a cv-qualified raw pointer or not, whereas your example uses the type std::shared_ptr, a pointer-like container type. You can start by defining your own trait to detect the appro... |
66,976,865 | 66,995,988 | QProcess how to request windows UAC to bypass password using runAs for admin level commands from an admin account | Question: Can anyone explain to me how to call UAC? At this point, I need to elevate a Powershell session. All of the other methods I've used in the past or see here require a password. I need to bypass the password. Please see the write up under the following function for more information:
void MainWindow::execute_com... | So, @RbMm was correct, my code was wrong:
void MainWindow::execute_command(QString param)
{
SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = "runas";
ShExecInfo.lpFile = ... |
66,976,993 | 67,490,867 | How to maintain compatibility between gcc 7 and gcc 9 with -Ofast | I have library which I have compiled on Ubuntu 18.04 using the version of gcc which comes bundled in the build-essential package, gcc 7.5.0.
If I then try to compile an application on Ubuntu 20.04 and link against the that library I previous built using the default gcc version, gcc 9.3.0, then I get a bunch of errors s... | Based on the comments, it looks like it is not compatible because of the use of the -Ofast compiler optimization flag.
|
66,977,216 | 66,977,480 | Dev C++ gives one output, but Visual studio code gives another output for same code | Dev C++ gives one output, but Visual studio code gives another output for same code
Why is this happening?
Any ideas, maybe it is caused by diffrent compiling options, or some mistake in code up here.
Ask if you need more info, I have no idea why this is happening.
If this happends to such a small code what will happen... | Try this solution. start the variable j at 1 and compare line[j - 1] with line[j]. j will be max 9 in this case.
#include <iostream>
using namespace std;
int main()
{
int line[10];
bool growing = false;
cout << "Input 10 numbers:\n";
for (int i = 0; i < 9; i++)
{
cin >> line[i];
}
... |
66,977,394 | 66,977,875 | Passing a nullptr to my overloaded function causes a runtime error | To understand more using directives and function overloading I've tried this program:
namespace ns{
void f(int){cout << "int\n";}
void f(double){cout << "double\n";}
void f(std::string){cout << "string\n";}
struct Foo{};
}
void f(ns::Foo const&){
cout << "ns::Foo\n";
}
namespace bin{
void f(in... | When using namespace bin; is commented out, there is only 1 version of f() available that can take a nullptr as input. nullptr is not implicitly convertible to int or double, so ns::f(int) and ns::f(double) are ruled out. But std::string can be constructed from a const char*, and nullptr is implicitly convertible to co... |
66,977,448 | 66,977,549 | C++11 char array intializations and string literals | In C++11, char pointers cannot be initialized to string literals directly.
In earlier versions of C++, I could do this with no issue.
If the code below is allowed:
char arr[] = "Hello";
char *p_str1 = arr; //allowed
Then why is the code below not allowed?
char *p_str3 = "Hello"; //Not allowed
Note: I am aware adding... | char arr[] = "Hello" stores a modifiable copy of the string literal "Hello" in the char array arr. p_str1 is a pointer to that array, and the data is modifiable, so the pointer does not need to be const.
char *p_str3 = "Hello" is a pointer directly to a string literal that is read-only. The pointer does not own the str... |
66,977,477 | 66,977,641 | In which ISO C++ version were iterators introduced? | I'm looking for a reference when iterators were introduced to the ISO C++, I can notice in this example they are used with vectors since C++98, but I read from the www.isocpp.com page that this is not official documentation but only a reference: http://www.cplusplus.com/reference/vector/vector/vector/
// constructing v... | Iterators go all the way back to ISO/IEC 14882:1998 (C++98). Using the link to the C++98 draft from here, can see that it has chapter 24 Iterators library in it1 and there it details the iterator requirements, std::iterator_traits, and std::iterator in it.
1: page 509 of the standard, page 535 of the PDF
|
66,977,634 | 66,977,713 | Usage of base class type pointer to the derived type object | Suppose we have the following code:
class Base
{
public:
virtual void print()
{
cout << "I'm base" << endl;
}
};
class Derived : public Base
{
public:
void print() override
{
cout << "I'm derived" << endl;
}
};
int main()
{
Base* b = new Derived();
b->print();
}
What ... | In your particular code, there is no real benefit in using the first method over the second. However, consider when you have two (or more) derived classes and want to use a common pointer to an instance of one of those classes, the actual type depending on some (run-time) condition. That's when such polymorphism shows ... |
66,977,805 | 66,977,833 | why can't I convert a lambda to a std::function here? | I need a function that generates other functions. Why doesn't the following not let me convert a lambda to a std::function? I've done that before.
#include <iostream>
#include <functional>
std::function<int()> funcGen(int param) {
std::function<int()> myGeneratedFunc =
[param](int input) -> int {
ret... | std::function<int()> accepts a function which takes in no arguments and returns an int. Your proposed lambda takes in an int and returns an int.
Consider std::function<int(int)> instead:
#include <iostream>
#include <functional>
std::function<int(int)> funcGen(int param) {
std::function<int(int)> myGeneratedFunc =... |
66,977,846 | 66,978,013 | Problem accessing object attributes from a pointer class attribute | I have the following class:
class Customer {
private:
string name;
savingAccount *savingsAccount = nullptr;
public:
void setSavingsAccount(savingAccount savingsAccount);
savingAccount* getSavingsAccount();
And methods:
savingAccount* Customer::getSavingsAccount()
{
return this->savingsAccount;
}
vo... | Customer::getSavingsAccount() returns a pointer to a savingAccount object. To access members of that object, you need to dereference the pointer using the * operator, and then access the members using the . operator. Or, you can use the shorter -> operator:
(*customer.getSavingsAccount()).getBalance()
customer.getSav... |
66,977,862 | 66,978,052 | Nlohmann::json& as function argument without including json.hpp in header | I have a class where I want to have a function that uses nlohmann::json& as the argument:
class MyClass
{
public:
void foo(nlohmann::json& node);
};
But I don't want to include the json.hpp file in my header, just my .cpp. How can I declare the nlohmann::json in the header? I tried:
namespace nlohmann
{
class... | If we have a look at the source, we can see that json is defined in json_fwd.hpp.
using json = basic_json<>;
json is an alias for basic_json so you need to forward declare basic_json before you can declare json. If you scroll up a bit in json_fwd.hpp, you'll see the massive forward declaration for basic_json. So if yo... |
66,977,885 | 66,978,605 | How Can I Read in a Graph to an Adjacency Matrix In the Boost Graph Library? | In the boost graph library, there are two popular functions to read in graphs from a file:
boost::read_graphviz(), and boost::read_graphml(), for the GraphViz and the GraphML format, respectively.
Now both read generically to any type of boost::adjacency_list<...>, as they are models of the Mutable Graph concept:
#incl... | Regarding copy_graph
What I don't understand is, that for copying, the (copy target) graph apparently also has to be a Mutable Graph, so how can we then copy to an adjacency matrix? And not read into one?
I agree. That doesn't make sense. For all it appears the copy_graph should not work or the documented concept req... |
66,978,211 | 66,978,390 | Passing variables to a constructor with multiple inheritance | I am having problems passing up two pieces of data through my classes, ID and Name specificly. I understand that you cannot call the base class constructor up without going through the previous parent classes but I am struggiling to fiugure out why this is not working, do I need constructors all the way up or can I jus... | Writing a minimal reproducible example really isn't that hard; you remove whatever isn't needed while still demonstrating the problem. In this case, it might be:
class CEmployee
{
char m_name[30];
char m_id[30];
virtual float Pay() = 0; // pure virtual function
public:
CEmployee(char name[], char id[])... |
66,978,252 | 66,978,274 | How to check if a template argument is of a particular templated type (multiple type parameters) | I asked a question yesterday (How to find out if a type is a templated type of any type?) about how to check for a particular template argument when that argument is a templated class of any type. And the solution was something like this:
template <typename T>
struct Animal{};
template <typename T>
struct IsAnimalOfAn... | You can declare all the template parameters required by Animal for the specialization.
template <typename T, T integer, typename U>
struct IsAnimalOfAnyType<Animal<T, integer, U>>
{
constexpr bool value() { return true; }
};
LIVE
|
66,978,268 | 66,978,296 | How can I stop ostringstream (oss) from adding to/overwriting predefined variables? | I'm relatively new to C++ and have come across the use of ostringstream oss as a way to include variables in an output and set it as a string.
Ex.
string getDate(){
oss << _month << "," << _day << "," << _year ; //date format
string date = oss.str(); //date as a string
return date;
}
My issue is that every time I c... | If you want to clear your stream, there are two choices.
Use local stream
string getDate(){
std::ostringstream oss;
oss << _month << "," << _day << "," << _year ; //date format
string date = oss.str(); //date as a string
return date;
}
Clear your stream after use
string getDate(){
oss << _month ... |
66,978,577 | 66,978,599 | Why is it not possible to overload insertion operators in c++ for a dynamic array? | I'm new to C++. Just out of curiosity, I'm trying to see what happens when I try to overload the insertion ">>" operator for a class of dynamic array. I think what I'm trying to do is impossible. But could anyone explain what this error means? (error below the code)
#include<iostream>
using namespace std;
template<cla... | Your friend declaration refers to a non-template operator>>, which doesn't match the definition of the template one.
Make the friend declaration refering to the template operator>>, e.g.
// forward declaration for the class template
template<class Type>
class Array;
// declaration
template<class Type>
istream& operator... |
66,979,238 | 67,014,430 | When does Eigen matrix release heap memory? | I would like to write a very very tiny matrix/tensor library with minimal features, and API like Eigen.
What confused me is, setting a debug break point, does not take me into some destructor function, I get nothing.
To reproduce, use this snippet that uses Eigen:
#include <Eigen/Dense>
#include <stdio.h>
#include <ios... | This is the compiler and debugger difference, after tried difference tools and methods from comments in this problem description.
The Visual Studio 2019 (until 2021-4-9, version 16.9.3) still can't debug step into DenseStorage class's destruction function.
While, Visual Studio 2019 with clang-cl, and lldb/gdb with clan... |
66,979,528 | 68,388,393 | How to dynamically create a 2d vector | vector< vector<int>> arr(n);
arr is a 2d vector. I want to take input "columns" from user and then the elements.
for(int i=0;i<n;i++)
{
int cols; cin>>cols;
//Statements
}
How shall I create the cols sized vector inside that for loop?
| I finally did it like this.
#include<bits/stdc++.h>
using namespace std;
int main()
{
//rows=5 and columns are dynamically initialized
vector<vector<int>> v(5);
int cols;
for(int i=0;i<5;++i)
{
cout<<"Enter column count for row : "<<i+1<<"\n";
cin>>cols;
v[i]=vector<int>(cols... |
66,980,425 | 66,983,381 | Zeroing memory without optimization | As you know, we cannot use memset() for zeroing a memory if it is not accessed later because it may be optimized by compiler. I saw a suggestion in cpp ref that we can use std::fill with a volatile pointer to solve this problem. Now here are my questions:
Does this statement means if the pointer is not volatile, std::... | Yes, this will work:
volatile int* ptr = vec.data();
std::fill(ptr, ptr+vec.size(), 0);
The one thing that prevents the compiler from optimizating it away is the volatile keyword (this is basically the whole purpose of that keyword), so std::fill with a non-volatile pointer will also be optimized.
Since memset is defi... |
66,980,693 | 66,981,257 | How does the following Binary Search Tree node removal method work? | The doubt is concerning the final deletion step (in the final else statement) and how the parent nodes reference to child node is reassigned.
The code is from the book Data structures and Algorithm analysis in C++ by Mark Allen Weiss.
Reference of entire code: https://users.cis.fiu.edu/~weiss/dsaa_c++3/code/BinarySearc... | In the remove function's signature, BinaryNode * & t is a reference to a pointer of type BinaryNode. That is, it is a reference to the parent's left/right node pointer.
I made a simple diagram for you, since "a picture is worth a thousand words".
So basically, it first saves the actual pointer the reference is referenc... |
66,980,878 | 66,981,001 | How to instantiate an abstract class without using new and delete? | Consider following code,
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0;
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void meth... | You need a pointer or reference to the object for polymorphism to work, but you can create that object in whatever way you want.
Concrete c;
c.method1(); // no polymorphism, using concrete directly
c.method2();
Interface* f = &c;
f->method1(); // polymorphism through Interface pointer
f->method2();
Interface& f2 = ... |
66,981,421 | 67,044,059 | What is the correct way to share plugins for programs within a super build? | Take the following example sturcture of a project:
.
+-- CMakeLists.txt
+-- app1
| +-- CMakeLists.txt
+-- app2
| +-- CMakeLists.txt
+-- app3
| +-- CMakeLists.txt
+-- plugins
| +-- plugin1
| +-- CMakeLists.txt
| +-- plugin2
| +-- CMakeLists.txt
| +-- plugin3
| +-- CMakeLists.txt
+-- tests
|... | I have now wrote a script which utilises https://cmake.org/cmake/help/latest/module/BundleUtilities.html which got run at build and install time. All plugins which are configured to build are added to a list which will be used to copy the needed dlls into the executable dir. fixup_bundle(all_executables all_plugins add... |
66,981,772 | 66,981,860 | Returning std::span from a function | Yesterday I started to use std::span because it's really handy, so I wanted to know if I'm getting std::span out of function correctly. Is it correct?
std::span<std::uint8_t const> span1;
if (read_data(&span1))
return 0;
// function
int read_data(std::span<std::uint8_t const>* output)
{
uint8_t* address = ...
... |
Is it correct?
A bit hard to tell when you omit the most important bit and replace it by a pair of ....
Assuming the buffer is not of automatic storage duration and persists beyond the function call... Then yes, it's not immediately wrong. But if you intend for the span to own the buffer, you'd soon get into trouble.... |
66,981,830 | 66,981,909 | Call function with variadic arguments where variadic arugments are references | I try to implement a class which accepts a function and a variadic argument list as input to execute these functions later on a worker thread. My current implementation has a problem, if one of the arguments is a reference.
Have a look at the following smaller code example:
#include <functional>
#include <iostream>
te... | My recommendation is that you take a look at how the standard library itself uses templates to pass callable objects (functions, lambdas, etc.): By using a single template type:
template<typename Func, typename ...Args>
auto Foo(Func f, Args&&... args)
{
return f(std::forward<Args>(args)...);
}
Note that I have ad... |
66,981,857 | 66,999,427 | Accessing Index buffer in shaders (Directx 11) | I have a vertex and index buffer and I am rendering a mesh to just one pixel and I want to know which triangle of the mesh is rendered and access its index in index buffer on cpu for further process(Base on my mesh only one triangle can rendered to that pixel).
I first implement it with SV_PrimitiveId and I hope it wou... | This should work:
C++:
...
Microsoft::WRL::ComPtr<ID3D11Texture2D> pPrimitiveIDs;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> pPIDsRTV;
Microsoft::WRL::ComPtr<ID3D11Texture2D> pPIDsStaging;
...
const int number_of_rtvs = 2;
ID3D11RenderTargetView* rtvs[number_of_rtv... |
66,982,476 | 66,982,542 | How to get a random int from a multidimensional array in c++ | I'm looking to get a random int from a 2d array like this:
static const int points[6][3] = { {2,3,4}, {11,12,13}, {14,15,16}, {17,0,1}, {8,9,10}, {5,6,7} };
The output could be any number within the array.
| You can use rand from <stdlib.h> in combination with time from <time.h>:
srand(time(NULL));
/* get random element */
int y = rand() % 6;
int x = rand() % 3;
int r = points[y][x];
Alternatively you could use <random> which is preferable, as mentioned by jabaa in the comments:
std::random_device rd;
std::mt19937 gen(rd(... |
66,982,766 | 66,983,442 | How to make a code that prints a text and makes it stay in a window? | So, if you don't really know what do I mean, there's a small explanation. I'm also new in C++ so I need help with some things, so yeah. There's the explanation.
If you make a code, for example
cout << "Hello world!";```
-- I forgot how to make it fully good, but that's an example
Then it prints and closes extremelly f... | I am assuming you are talking about console window that closes fast.
In order to prevent that there are multiple ways of doing it. But i will write two simplest ways of doing so.
Add header at the top of your C++ program
#include <stdlib.h>
Then in the end of main function just before return 0 write this line of co... |
66,983,156 | 67,007,120 | Is coercion static or dynamic polymorphism? | Parametric polymorphism and overloading are static polymorphism, because the compiler knows at compile-time which function to call.
Subclassing is dynamic polimorphism, beause the function gets determined at run-time. But what is coercion (implicit casting)? Static or dynamic polimorphism?
The compiler knows at compile... | Runtime polymorphism involves (potentially) several distinct bits of machine code being selected from based on some runtime data related to the runtime type of data involved, and that selection happens at runtime. (I say potentially because you can use virtual dispatch when there's only one concrete derived type, but ... |
66,983,572 | 66,983,793 | How to delete object on heap without causing segmentation fault | Hi (i am a C++ student trying to learn plz don't roast me ty in advanced),
I created temArr as on object on the heap. My program compiles with no problems when i run it without deleting temArr which is on the heap but there is memory leaks on temArr when i run it through valgrind. But when i run it with delete temArr... | If you uncomment your delete temArr line, your return statement is trying to access temArr variable, after it has been delated. That's undefined behavior, and anything can happen, from getting a random value to segfaults.
Your temArr doesn't need to be dynamically allocated, just create it on the stack, there's a quest... |
66,984,042 | 66,984,097 | Could not convert from ‘<brace-enclosed initializer list>’ to vector | The following vector declaration:
vector<string> valid_escape = {'n', 't', 'r', '0', '\\'};
Causes the error:
error: could not convert ‘{'n', 't', 'r', '0', '\\'}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<std::__cxx11::basic_string<char> >’
Other SO posts about this issue came to the conclusion tha... | If you need a std::vector of std::strings intialized with a single std::string composed by those characters, you need an extra brace initializer:
vector<string> valid_escape = {{'n', 't', 'r', '0', '\\'}};
The inner brace will initialize a string with the given characters, the outer brace will construct a vector with ... |
66,984,347 | 66,984,830 | PostMessage — how to send int array? | How to send int array:
int *pars = new int[4];
pars[0] = 87675;
//...
pars[3] = 1024;
PostMessage(?);
And then properly receive it and clear memory:
LONG OnMessage(WPARAM wParam, LPARAM lParam) {
//?
}
Everything in one process.
| Within a single process you can just pass addresses via LPARAM.
int *pars = new int[4];
pars[0] = 87675;
//...
pars[3] = 1024;
PostMessage(hWnd, WM_MY_CUSTOM_MSG, 0, (LPARAM)pars);
Then take it from lParam, use and then free:
LONG OnMessage(WPARAM wParam, LPARAM lParam) {
int *pars = (int*)lPar... |
66,985,057 | 66,985,306 | BMP-format Where are 2 bytes? | I have got a .bmp picture(24-bits). It is small(65x65) and its size is equal to 12796 bytes.
But let is compute:
54 bytes for header
65*65*3 bytes for pixels
1*65 bytes for padding for each line.
== 12794
Where can be 2 extra bytes?
And second question: do I use correct formula for computin padding?
int padding =... | bmp.width is in pixels. A BMP row is padded to 4 bytes. To get from pixels to bytes, multiply it by bitsPerPixel/8. Then pad that to 4.
Something like this:
int rowSizeInBytes = ((bmp.bits * bmp.width + 31) / 32) * 4;
Then, you should not assume header size is 54, take it from bmp.headersize instead.
Assuming a header... |
66,985,242 | 66,986,154 | Confusion about pointers | I am working on some code where I call two functions.
function1(SerializedMsg *source, void *target) deserializes the information in source and fills target with it.
function2(std::shared_ptr<Msg> &msg). To this function I feed messages created with function1.
My problem relates to pointers, I believe. I have tried... | When you are using pointer you need to take care where they point to and if there is some valid memory.
Taking your first approach:
std::shared_ptr<Msg> msg;
function1(&source, &msg);
You pass in the shared_ptr so the void* in you function points to the memory of a shared_ptr. Not the memory the shared_ptr points to.
... |
66,985,286 | 66,985,425 | How to save data pointed by a pointer in c++ to txt file? | I have a code which contains pointers and other variables.
Some example pointers are:
int* bias;
float* coordLin;
float* coordTarget;
float* graphLin;
int* facesLin;
int* neighReg;
float* embeddedWeights;
float* affGraph;
After doing some calculations, I need to save data from these pointers to a file. If I directly u... | You have to dereference pointers. Use * before name and then write value to file.
int biasValue = *bias;// gives you value of bias
float coordLinValue = *coordLin;// gives you value of oordLin
|
66,985,606 | 66,985,813 | for loop with invalid error and looping questions | I am fairly new to C++, I am trying to write a code that allows input number of reviewers then allows number of reviewers to enter movie rating and display asterisks based on the number input. I am having difficulty incorporating an if statement that display "Movie ratings must be from 1 to 5." when the user input any ... | You should have
#include <iostream>
#include <string>
using namespace std;
int main(){
int reviewers;
int rating;
//input how many reviewers will be reviewing
cout << "How many reviewers? ";
cin >> reviewers;
cout << "Movie ratings must be from 1 to 5." << endl;
for (int r = 1; r <= reviewers; r++) {
cout ... |
66,985,932 | 66,986,187 | Switch WiFi mode from AP to STA | I'm working on project with ESP32-S2-Saola-1M board in C/C++ via ESP-IDF framework. At the beginning I initialize a Wi-Fi in an AP mode and starts the HTTP WebServer to get WiFi data from user through browser. After the user saves his Wi-Fi data (SSID and Passwd) throught page, the
HTTP server should shut down and Wi-F... | By far the easiest approach is to just reboot (esp_restart()) after saving new configuration.
Then select the right mode after reading the configuration on boot.
void app_main()
{
// init NVS
// load configuration from NVS
if (config.wifiSSID.empty()) {
startAPmode();
} else {
startSTAmo... |
66,986,595 | 66,999,747 | Multiple inheritance with two interfaces, one which derives from first, and a derived class implementing the first interface | Sorry for the poor description. Here's the issue:
class PureVirtualBase {
public:
virtual ~PureVirtualBase() {}
virtual int IntFn() = 0;
};
class PureVirtualDerivedBase : public PureVirtualBase {
public:
virtual ~PureVirtualDerivedBase() {}
virtual int OtherIntFn() = 0;
};
class Foo : public PureVirt... | The mistake is in how virtual inheritance is being applied.
Specifically, this problem can be fixed by using virtual inheritence, just not in the way first described (i.e. not "public virtual Foo, public virtual PureVirtualBase").
Both Foo and PureVirtualDerivedBase need to virtually inherit from PureVirtualBase:
class... |
66,986,718 | 67,128,620 | C++ Clang emit warning about unused template variable | C++ Clang emit warning about unused template variable
Considering an unused template variable definition, such as this one :
template <typename T, typename = void>
struct is_complete : std::false_type {};
template <typename T>
struct is_complete<T, std::void_t<decltype(sizeof(T))>>
: std::true_type {};
template <ty... | The heuristics for the Clang "unused" class of diagnostics don't appear to inspect each instantiation at all, but rather the uninstantiated template itself.
I've experienced similar issues myself, specifically when relying on constructors within template functions to produce side effects (for RAII, etc.). When Clang ne... |
66,986,774 | 66,987,085 | Is variable defined out of scope Optimized? | So, some may agree that (code 1):
void func()
{
int a, b;
{
//Do something with a and b
}
}
Looks better (or is a better practice) than (code 2):
void func()
{
int a;
{
int b;
//Do something with a and b
}
}
Also, than this (code 3):
void func()
{
{
int a, b... | For trivial types (and this has a technical meaning), the destruction/creation of them simply indicates where the compiler is guaranteed not to need to know what their values are. Any possible danging reference or pointers after the variable goes away can be "ignored" when optimizing.
So creating data in the smallest ... |
66,987,040 | 66,987,220 | Split a string of tab separated integers and store them in a vector | ifstream infile;
infile.open("graph.txt");
string line;
while (getline(infile, line))
{
//TODO
}
infile.close();
I am taking input line by line from the file and storing each line in the string "line".
Each line contains integers separated by tabs. I want to get these integers separated and store each integer i... | The duplicate has some solutions, I would, however, prefer to use a stringstream, something like:
#include <sstream>
//...
vector<int> v;
if (infile.is_open()) // make sure the file opening was successful
{
while (getline(infile, line))
{
int temp;
stringstream ss(line); // convert string int... |
66,987,109 | 66,987,684 | Read a collection of dates | How to read a number of dates and store them in a array/vector in C++? For examples I have:
6
20 1 2014
25 3 2010
3 12 2001
18 11 2001
19 4 2015
9 7 2005
where 6 is the number of given dates. Each date is separated by a space.
This is my attempt:
std::cout << "Enter the number of dates to enter : ";
int num_dates;
std... | I believe that you don't want to separate the date to day, month and year, but just save it into array. My solution:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::cout << "Enter the number of dates to enter: ";
int num_dates;
std::cin >> num_dates;
std::vector<std::string> ... |
66,987,300 | 66,987,378 | Destructor called two times in C++ | I have a code with two classes like this:
Class A:
class A {
int a, b;
public:
A(int x, int y) {
a = x;
b = y;
}
~A() {
cout << "Exit from A\n";
}
void values() {
cout << a << "\n" << b << endl;
}
};
Class B:
class B :public A
{
int c;
public:
B(int x... | There are 2 A objects created in main, testA, and the A base-subobject of testB. Both are destroyed at the end of main, in reverse order of how they are declared.
class A {
int a, b;
std::string msg;
protected:
A(int x, int y, std::string m) : a(x), b(y), msg(m) {}
public:
A(int x, int y) : A(x, y, "Exi... |
66,987,392 | 66,987,669 | atoi() always returning zero if false | I use atoi() to convert argv to int, the problem is when argv = zero is a considered parameter in my problem, it will return zero as well.
I tried to loop about all the arguments except file name for sure, what to do ?
for (int i = 2; i < argc; i++) {
if (!atoi(argv[i]) && atoi(argv[i]) != zero) {
std::cout... | You can do the following.
SO your Problem is that you can't determine if your argv[i] contains either a numeric 0 or a letter or other sign.
for (int i = 2; i < argc; i++) {
for(int x = 0; x < strlen(argv[i])){
if(!isDigit(argv[i][x])){
std::cout << "invalid" << std::endl;
return 0;
... |
66,987,537 | 66,988,230 | C++ error : non deleted function cannot override a deleted function | I implemented the following base class and derived classes respectively
class observerInterface {
public:
virtual void update(std::string data) = delete;
virtual const std::string & getUniqueID() = delete;
private:
//deleting copy constructor and copy operator.
observerInterface(const observerInterface... | Here you are deleting the functions:
virtual void update(std::string data) = delete;
virtual const std::string & getUniqueID() = delete;
These functions are deleted and their use is disabled by the compiler.
If instead, you intend to force these functions to be overriden, you should instead use:
virtual void updat... |
66,987,676 | 66,988,082 | Using concept inside class declaration | The struct Vec has all the requirements to be std::default_initializable. But the declaration is not finished, so it failed to compile.
template <std::default_initializable A>
struct It {};
struct Vec {
using Iterator = It<Vec>;
};
Is there some sort of workaround to keep the It requirement ?
| In general, the answer to your question is no. If you want to make a member type alias, it has to be known at the time in question. And if the template you're trying to instantiate requires that the type it is given is complete (which default-initializable does), then it must be complete.
In your specific case however,... |
66,987,844 | 66,987,973 | Is it correct to call a base class method on derived class objects when overloading output / input operator for derived class? | Let's say we have those 2 classes "
class parent {
protected:
float pr;
public:
/// constructors, copy constructors, operator= overloading ...
float get_pr() const
{
return pr;
}
friend ostream& operator<<(ostream& pout, const parent &obj1)
{
... | Well that's the basic idea of inheritance. child is a parent and therefore has a method float get_pr() const. So it's totally fine to call a base class method from a derived class.
A derived class (child in your case) inherits everything from it's parent class and can access every public and protected member of it.
|
66,988,477 | 66,992,982 | Is it legal c++ to use reference as array/pointer? | My team (including myself) is new to C++. A piece of our new development is a C++ function that needs to interface with a C function that takes an array as input. Something like the following construct was made to achieve this:
#include "stdio.h"
void the_c_function(double *array, int len)
{
for (int i = 0; i < len... | The question of code readability aside,
is it guaranteed that a pointer to a reference of an array points to the original array?
Yes, see § 5.5 Expressions:
If an expression initially has the type “reference to T” ([dcl.ref], [dcl.init.ref]), the type is adjusted to T prior to any further analysis. The expression de... |
66,988,496 | 66,988,525 | warning: control may reach end of non-void function problem | Well, i made RGB To Hex Conversion. My programm in online compiler works pretty well, but on codewars it has a problem "control may reach end of non-void function". What should i do? Should I remove for loop?
using namespace std;
#include <iostream>
#include <string>
int checkForNumber(int input) {
if (input > 255... | The problem is in your check(int input) function -- consider what happens if the value of the input argument is not in the range [10, 15]. I suggest putting in a default: case that returns something appropriate at the bottom of your switch block.
|
66,989,112 | 66,989,428 | Make RGB LED Light up brighter? | I've been trying to make a traffic light simulator but am having trouble with making one RGB light up brightly (in the code it's referred to with (colour)Pin2). The first light works perfectly but the RGB on the left isn't working correctly. I succeeded in making it bright when the light is white, but when I try to mak... | You seem to be getting confused between digitalWrite and analogWrite. The digitalWrite function takes a pin number and either HIGH or LOW. Passing an integer value as you are in undefined. I would guess that an integer of zero will be off and any other value will be on.
It looks like you want to setup the pins as analo... |
66,989,716 | 67,007,435 | Passing CuPy CUDA device pointer to pybind11 | I am trying to instantiate an array in GPU memory using CuPy and then pass the pointer to this array to C++ using pybind11.
A minimal example of the problem I am running into is shown below.
Python
import demolib #compiled pybind11 library
import cupy as cp
x = cp.ones(100000)
y = cp.ones(100000)
demolib.pyadd(len(x)... | The fix was to change the argument types of pyadd to int and cast the int to float pointers as shown below. As pointed out in the comments, this was figured out by referencing another question.(unanswered at the time of posting)
int pyadd(int N, long px, long py)
{
float *x = reinterpret_cast<float*> (px);
float *... |
66,989,961 | 66,990,307 | Smart pointer vs regular pointer for performance | Is there an advantage or disadvantage to using smart pointers vs regular pointers regarding performance?
I am running the following code, compiled with VS2019 in release and debug.
These are the results for release:
Assign Ptr time = 0.3285ms
Assign Smart ptr time = 0.101ms
Sum Ptr = 126756464
Sum Smart Ptr = 126... | In release mode, what you're seeing is just noise. A unique_ptr is going to get compiled out. You can see this from the compiled assembly (g++ output from the assign shows):
Raw Pointer
mov edx, 1000000
mov rsi, rsp
mov rdi, r13
mov rbp, rax
call memcpy
Unique... |
66,990,007 | 66,991,630 | Avoid writing constructor every union style class in C++17 | I'm stuck with c++17 for a project, so I don't have access to designated initializers. I have a bunch of union types that I want to avoid initializing this way (because it is annoying):
MyUnionType x;
x.value = value_set_for_all_union_members;
I want to instead have this
MyUnionType x(value_set_for_all_union_members)... | Not exactly what you asked... but you can use the fact that you can use the type of D::value inside a member function... so using SFINAE over a template contructor...
I mean, you can write something as
template <typename D>
struct Base
{
template <typename T>
static constexpr bool is_value_type ()
{ return s... |
66,990,572 | 66,990,721 | Function overload. The operation inside the function is the same. Do I have to rewrite everything? | I have a bunch of functions with input x and y. I allow input type to be either pass by reference (if it is already there) and pass by temporary input (using &&) (if not exist and need to create a temporary object).
Basically, I define and overload functions as follow
double foo(const std:::vector<int> & x, const std::... | Instead of writing four overloads, you can do this with a single function template. Doing that would give you a function like
template <typename Vec1, typename Vec2,
std::enable_if_t<std::is_same_v<std::decay_t<Vec1>, std::vector<int>> &&
std::is_same_v<std::decay_t<Vec2>, std::vec... |
66,990,956 | 66,991,068 | Initialize boost::optional with ternary operator | Is the a way to initialize optional like:
bool conditional = true;
boost::optional<int> opt = conditional ? 5 : boost::none;
Why does the error occur?:
main.cpp:31:31: error: operands to ?: have different types ‘int’ and ‘const boost::none_t’
boost::make_optional(cond ? 5 : boost::none);
| ... | The ternary operator requires the left & right to be the same (or convertible) types. none_t and int aren't the same type. You can probably do cond ? boost::optional<int>(5) : boost:none
I don't use boost, so just guessing on syntax based on std::optional, but the following does work:
std::optional<int> opt = cond ? st... |
66,991,188 | 66,998,832 | Can not covert from 'const char*' to 'char*' in VS19, although earlier could | I bought a Surface Go 2 today, and installed Visual Studio 2019. I loaded my project, that successfully compiled on my previous PC, also in VS19.
The first problem that I noticed is that the VS editor displays Unicode characters (Cyrillic) in my .cpp files as hieroglyphs:
card->NewTextW(L"Çàãðóçêà", ...
Instead of:
ca... |
Cannot covert from 'const char*' to 'char*' in VS19, although earlier version could
According to the doc: /permissive- (Standards conformance)
By default, the /permissive- option is set in new projects created by
Visual Studio 2017 version 15.5 and later versions. It's not set by
default in earlier versions. When th... |
66,991,323 | 66,991,676 | Variable unexpectedly changed to 0 after cin to different variable | I have a problem with my program in c++: this program unexpectedly sets my variable n_alunni to 0 when I cin >> verify; even though I haven't written anything else to n_alunni.
This is the code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n_alunni=1;
char verify[1];
cout<<"... | As Peter said in his answer, and TomLyngmo in his comment, trying to cin to a char[] (verify) makes C++ think you want to write a C-string, which always has a 'null terminator' to indicate the end of the string. However, your char[] is only length 1, so unless you don't insert anything into it, it will try to write bey... |
66,991,439 | 66,991,891 | Why i can't call base class operator>> in derived class operator>>? | Let's say we have 2 classes :
class base{
protected:
char first_name;
public:
/// constructors , destructor, operator= overloading ...
friend istream& operator >> (istream& in, base &client1)
{
char f_name[1001];
cout << "First Name: ";
in >> f_name;
client1=base(... | You have fallen prey to object slicing. You can fix the immediate problem by casting to a reference.
In
in >> (base) client2;
what's really happening is a new temporary Base is made from client2, discarding all of derived's added members. This is legal. The compiler gets upset because the temporary Base cannot be used... |
66,991,556 | 66,991,776 | C++: Does Comparing different sized integers cause UB? | So this is probably a really simple question and if it was not about C++ I would just go ahead and check if it works on my computer or not, but unfortunately in C++ things usually tend to work on a couple of systems while still being UB and therefore not working on other systems.
Consider the following code snippet:
un... | This is not undefined behavior. This is covered by the usual arithmetic conversions which are detailed in section 8p11.5 of the C++17 standard:
The integral promotions (7.6) shall be performed on both operands.
Then the following rules shall be applied to the promoted operands:
(11.5.1) If both operands have the sam... |
66,991,675 | 66,991,717 | Template function for increasing and decreasing priority queue | I wanted to write a template function for printing increasing and decreasing priority queues. Currently I have implemented it as
void print_queue1(priority_queue<int> q, string s){
cout << "Value of prior queue " << s << " is : [";
while(!q.empty()){
cout << " " << q.top() << ",";
q.pop();
... | You can use a variadic function template for this. Since the logic is the same regardless of the queue type, we can just accept any type of queue like
template <typename... Params>
void print_queue(priority_queue<Params...> q, string s){
cout << "Value of prior queue " << s << " is : [";
while(!q.empty()){
... |
66,991,729 | 66,992,473 | What's the Time Complexity and Space Complexity this function to check valid parenthesis? | I am unable to find the Time Complexity and Space Complexity of the code to check valid parenthesis. Can anyone help, please?
code -
bool isValid(string s)
{
int s_size = s.length();
for (int i = 0; i < s_size-1;i++)
{
if((s[i]=='(' && s[i+1]==')') || (s[i]=='[' && s[i+1]==']')|| (s... | For just the code snippet you posted above, the time complexity is O(n3).
As rightly pointed out by n. 'pronouns' m., the outer for loop for (int i = 0; i < s_size-1;i++) runs n2 times because i resets to the starting point every time a match is found. And the s.erase() function also takes O(n) time to run. In total ma... |
66,992,020 | 66,992,204 | serial write to COM port using C/C++ from MATLAB reference code | I am using a simple matlab code to send serial data to a COM port device, however I am having issues and would like an equivalent C/C++ code to achieve the same result. Shown below is the MATLAB code.
s_port = serialport('COM1',9600);
configureTerminator(s_port,'CR');
write(s_port,char([50 01]),"char");
pause(1)
writ... | Because the port is named "COM1" and not "/dev/ttyS0" I assume you are running on Windows.
You can fopen("COM1:") and fwrite() to it, but that won't give you control over baud rate.
For control over serial port settings (baud rate, parity, stop bits, flow control), you need to use the Win32 API (CreateFile, build or mo... |
66,992,175 | 66,993,237 | How do I prevent the program from going into infinite loop when writing a char to a float form? | I made a Newton-Raphson Method program. But I have a question. As you see, "epsilon" and "x0" are float type and when I try to write something like "a" or "b", the program goes crazy. I want to prevent it. I want to tell "Please enter a number" to the user when something happens like this.
Can you help me about that? T... | The infinite loop problem occurs because cin and underlying ifstream expects a float in your case. By not providing a float, cin fails and the weird loop occurs. More information here.
Since you cannot control the user and you do not want the program to break if the user inputs characters, you can read the input to str... |
66,992,206 | 66,992,371 | Unable to print vector values from map in maps | I am trying to print out the whole contents of map of maps but keep encountering into issues.
Here is my map initialisation map<int, map<int, vector<int>>> myMap;
I have tried the following code:
for( auto const & cit : myMap)
{
cout << cit.first << " : ";
auto const & imap = cit.second;
for... | You need to do it like this.
for( auto const & cit : myMap)
{
cout << cit.first << " : ";
auto const & imap = cit.second;
for( auto const & cit2 : imap )
{
cout << cit2.first << ":";
auto const &vec = cit2.second;
for(auto const &i : vec)
... |
66,992,260 | 66,993,535 | How can I create an object inside a class in c++? | I want the object to be inside the class, but I can only do it inside a function:
This is basically what I want:
class Foo1 {
public:
Foo1(int a, int b) { /*stuf..*/. }
}
class Foo2 {
Foo1 foo1(2, 1); // oject here
public:
Foo2(int a, int b) { /*stuf...*/ }
}
| You can create the object and initialize it:
class Foo2
{
public:
Foo1 foo1{2, 1}; // using curly brackets, object created and initialized
// Or in the initializer list of the Foo2 constructor
// Foo1 foo1;
// Foo2() : foo1(1,2){}
};
Let's assume your class Foo1 has 2 int members a and b, only for fo... |
66,992,426 | 66,993,817 | Sorting the values of linked list and printing them | I have a list:
struct node
{
string name;
int value;
node* next;
};
For example, I save 5 elements to it.
Now I want to find the three greatest elements.
node* help = head;
for (int i = 0; i < M; i++)
{
node* help2 = head;
while (help->next)
{
if (help->next->value > help->value)
... | If you don't know sorting refer this link https://www.geeksforgeeks.org/sorting-algorithms/ to better understand the concept and types of sorting algorithms.
In this example we have used bubble sort algorithm to sort elements in descending order
//sort your linked list this way as you said you have 5 element in your li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.