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 |
|---|---|---|---|---|
74,661,183 | 74,661,671 | CUDA - problem with counting prime numbers from 1-N | I just started with CUDA and wanted to write a simple C++ program using Visual Studio that can find total number of prime numbers from 1-N. I did this:
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <cstdio>
#include <cmath>
static void HandleError(cudaError_t err,
const char* file,
... | The proximal issue is that when number is 9, floor(pow(number, 0.5)) is giving you 2, not 3 as you expect. As a result, 9 is incorrectly flagged as a prime.
here is a similar question. pow() (at least, in CUDA device code) does not have the absolute accuracy you desire/need when using floor() (i.e. truncation). You mig... |
74,661,324 | 74,662,173 | How do I detect hitting enter twice to let user exit from populating array with for loop? | I have to let user fill an array with 0-500 values, and at any moment they can exit entering the array with two consecutive empty value inputs (hitting enter twice).
Then the array displays, then it sorts itself, and finally displays again.
I have no idea how to capture enter twice in a row to exit the loop.
The best I... | Note: ASCII value of \n is 10.
Following is the tested and working code:
int GetUserArray(int UserArray[ARRAY]) {
int input = 0;
int exit_flag = 0;
int howmany = 0;
cout << "Please enter an integer values: ";
for (int i = 0; i < ARRAY; i++) {
input = cin.get(); //Stores ASCII value inside i... |
74,661,843 | 74,663,831 | Can someone explain why this doeasn't work? The default constructor of "B" cannot be referenced -- it is a deleted function | I'm currently making c++ project but this error is bothering me for long time and i cannot figure out why this doesn't work.
I was searching about this error but still i don't understand it.
Thanks in advance.
#include <iostream>
using namespace std;
class A
{
public:
int a = 0;
A(int _a) : a(a) {}
};
class ... | First, your member initialization list in A's converting constructor is wrong. a(a) should be a(_a) instead.
Second, A has a user-defined constructor, so its compiler-generated default constructor is implicitly delete'd.
Thus, B::a can't be default-constructed, so B's compiler-generated default constructor is also impl... |
74,662,193 | 74,662,237 | Merge Sort failing at deletion (Thread 1: EXC_BAD_ACCESS code 2 ) | I know I should be using vectors, but I want to get better at dynamically allocating arrays. I'm not sure where I went wrong. I'm creating a new array and deleting it.
void Merge(int *arr,int begin, int mid, int end){
int*arrB = new int[mid - begin + 1];
int i = begin;
int j = mid+1;
int k = 0;
... | void Merge(int *arr, int begin, int mid, int end) {
// Allocate the arrB array on the stack instead of the heap
int arrB[mid - begin + 1];
int i = begin;
int j = mid+1;
int k = 0;
// Initialize the k variable to 0 before using it to index arrB
k = 0;
while (i <= mid && j <= end) {
if (arr[i] <... |
74,662,221 | 74,662,256 | error: 'to' is not a member of 'std::ranges' | Facing issue
std::ranges::to
I am executing the below example from https://en.cppreference.com/w/cpp/ranges/to
#include <algorithm>
#include <concepts>
#include <iostream>
#include <ranges>
#include <vector>
int main()
{
auto vec = std::views::iota(1, 5)
| std::views::transform([](auto const v){ retu... | This is because std::ranges::to is only supported right now by MSVC 19.34
You can check on the status of compiler support for language and library features here: https://en.cppreference.com/w/cpp/compiler_support
For example this feature is listed un the C++23 library section as
C++23 feature
Paper(s)
ranges::t... |
74,662,545 | 74,662,595 | What does set(str.begin(), str.end()) mean? | I was going through this question on leetcode: https://leetcode.com/problems/determine-if-two-strings-are-close/solutions/935916/c-o-nlogn-sort-hash-table-easy-to-understand/
class Solution {
public:
bool closeStrings(string word1, string word2) {
if(word1.size()!=word2.size())
return false;
... | It creates a set of the characters in word1, which is just the unique characters and in a way that could be compared to another word without the number of occurrences or order mattering.
So, comparing sets made this way, "cat" and "taca" would have == sets. "cat" and "taco" would not. "cat" and "kat" would not, but "do... |
74,662,673 | 74,662,721 | fread() and fwrite() using strings | I'm trying to implement simple fread() and frwite() example using strings. The program gives me segfault or free(): invalid pointer errors. Below is the example code I'm working with.
#include <fstream>
#include <iostream>
static bool file_read(FILE* file) {
std::string value="abcd";
std::string retrieved;
... | if you want to access the actual character buffer inside std::string you need to use value.c_str()
the length of the string is not given by sizeof, use value.length()
you cannot read from a file directly into a std::string using fread. You must read it into an intermediate char [] buffer and load from there. Or use ifs... |
74,663,376 | 74,663,653 | regex_replace is returning empty string | I am trying to remove all characters that are not digit, dot (.), plus/minus sign (+/-) with empty character/string for float conversion.
When I pass my string through regex_replace function I am returned an empty string.
I belive something is wrong with my regex expression std::regex reg_exp("\\D|[^+-.]")
Code
#includ... | The string is empty because your regex matches each character.
\D already matches every character that is not a digit.
So plus, hyphen and the period thus far are consumed.
And digits get consumed by the negated class: [^+-.]
Further the hyphen indicates a range inside a character class.
Either escape it or put it at ... |
74,664,135 | 74,664,221 | Is it UB to modify a const object's member via its non-const reference? | class T {
public:
int v;
int &vRef;
public:
T() : v(0), vRef(v) {}
};
const T t; // note, it's a const object
t.vRef = 2;
printf("v: %d\n", t.v);
The code presented above compiles OK, and the const object's internal value did change.
Question. Is this Undefined Behavior or not?
| Yes. If the object is declared as const, then modifying it (through any means, be that a non-const reference like in your example, via const_cast or something else) is UB.
|
74,664,621 | 74,664,897 | How do I perfect forward as generically as possible? | I have this example:
template<class ValueType>
class MyTemplateClass
{
public:
MyTemplateClass(ValueType&& Value) : MyMemberVar{ std::forward<ValueType>(Value) } {}
private:
ValueType MyMemberVar;
};
int main()
{
int x{ 5 };
MyTemplateClass<int> Instance{ x };
return 0;
}
This code does ... |
Is there something wrong with my code?
Yes.
The constructor you have written:
MyTemplateClass(ValueType&& Value);
Value is not a forwarding reference here, it is just an rvalue reference. To make it a forwarding reference, the type of Value must be a template parameter of this particular function:
template<typename... |
74,664,672 | 74,664,699 | What is the purpose of returning 1 or 0 from a function? | int SeqList<ElemType>::InsertElem(const ElemType &e)//insert at the taild
{
if(length==maxLength)
return 0;
else
{
elems[length]=e;
length++;
return 1;
}
}
The purpose of this program is to implement a sequential list,and I want know the difference between return 1 and ... | In the code you have provided, the return statements are used to indicate the success or failure of the InsertElem() function. The function is designed to insert a new element into a sequential list, but it will only do so if there is enough space in the list to accommodate the new element. If the list is full, the fun... |
74,665,119 | 74,665,150 | Undefined reference to class from namespace in C++ | I'm new to C++ and trying to do a small quant project with paper trading.
I have a header file alpaca/client.h as follows:
#pragma once
#include <iostream>
#include <../utils/httplib.h>
#include <config.h>
using namespace std;
namespace alpaca {
class Client {
private:
alp... | It looks like you forgot to compile the client.cpp file. The error message is saying that the linker cannot find a definition for the Client class constructor.
Try compiling both main.cpp and client.cpp with the g++ command, like this:
g++ -I./src/alpaca src/main.cpp src/alpaca/client.cpp
|
74,665,520 | 74,669,850 | How to conditionally initialize a member of a struct? | I am beginning to learn C++ struct. After creating a struct named Person, I tried to declare a boolean variable named genderBoolean in the struct of Person, and a string variable named gender. I tried to use if-else statement for the following condition: if genderBoolean is true, then gender is male, but if genderBoole... | Here are a few different ways to handle it using a constructor and a setter. Keep in mind that adding a parameterized constructor means the struct does not have a default constructor so you'd need special care to put it in an array and such. Adding a default constructor is left to you. I would advise making the member ... |
74,666,955 | 74,667,188 | How to declare a function, that takes a range | I want to declare a function, that gets a range as input, outputs a single number and use it directly with ranges::views::transform of the range-v3 library.
The following works but I have to use a lambda that doesn't really do anything.
int64_t getGroupValue( ranges::input_range auto&& group ) {
return ranges::accu... | function template cannot be passed around.*
One way is wrap it inside lambda object as you already did, or you can write it as function object at first place.
struct getGroupValue_op{
int64_t operator()( ranges::input_range auto&& group ) const{
return ranges::accumulate( group, 1ll, ranges::multiplies() );... |
74,667,965 | 74,668,131 | C++ multithreaded version of creating vector of random numbers slower than single-threaded version | I am trying to write a multi-threaded program to produce a vector of N*NumPerThread uniform random integers, where N is the return value of std::thread::hardware_concurrency() and NumPerThread is the amount of random numbers I want each thread to generate.
I created a multi-threaded version:
#include <iostream>
#includ... | You can do with without any mutex.
Create your vector
Use a mutex just to (and technically this probably isn't ncessary) to create an iterator point at v.begin () + itsThreadIndex*NumPerThread;
then each thread can freely increment that iterator and write to a part of the vector not touched by other threads.
Be sure ... |
74,668,051 | 74,668,130 | how to copy a map <string, int> into a vector <int, string> | my code copies the map in the same order
map <string, int> to vector <string, int>
I want this instead
map <string, int> to vector <int, string>
is it possible with std copy?
#include <iostream>
#include <vector>
#include <map>
#include <iterator>
#include <fstream>
using namespace std;
int main(){
fstream fs;
... | Lots of different ways, but this will work
vector<pair<int, string>> v;
v.reserve(mp.size());
for (const auto& p : mp)
v.emplace_back(p.second, p.first);
Does't seem to be possible with std::copy since your value types are different and the source is not convertible to the destination. It should be possible with s... |
74,668,134 | 74,668,440 | My data show up 2 twice whil use function? Operation file C++ - Case: Delete Specific Line in c++ | I got a task that is:
Write a simple program that can be used to delete data on one
one line specified in a file with the following steps:
Manually create a file containing:
i. Fill from line 1
ii. Fill from line 2
ii. Fill from line 3
iv. Fill in line 4
Display the entire contents of the file.
Appears the choi... | This code is bugged in two different ways
void show_data(){
myFile.open("data1.txt");
while (!myFile.eof()){
getline(myFile,buffer);
output.append("\n" + buffer);
}
cout << output;
myFile.close();
}
The first bug is the incorrect use of eof. The second bug is the use of the global... |
74,668,400 | 74,668,443 | Can't find uninitialised value (valgrind) | So I'm making a queue list and I'm trying to get rid of memory leaks and uninitialised values. But when running with valgrind I keep getting Conditional jump or move depends on uninitialised value(s).
I tried to debug the code and find the error but I can't.
Here is the code I'm running:
#include <fstream>
#include <io... | In enqueue function, you do:
Node* newy= new Node;
if(List->tail == NULL){
List->head = List->tail = newy;
return true;
}
At this point, newy is a newly initialized Node object; however, none of its members have been set. You also don't adjust the size of the Queue.
Secondly, let's say that... |
74,668,523 | 74,668,732 | c++ recursive macro wont compile on MSVC? | I got this source code from [https://www.scs.stanford.edu/~dm/blog/va-opt.html]. Using MSVC with C++20 it doesn't compile, but it does compile on other compilers. Why? And how can I fix that?
`/* compile with:
c++ -std=c++20 -Wall -Werror make_enum.cc -o make_enum
*/
#include <iostream>
#define PARENS ()
// Resc... | The old preprocessor in MSVC is known to contain many problems, see e.g. this article by Microsoft. Their new preprocessor can be used via the /Zc:preprocessor flag, causing the preprocessor to be more standard conform and also closer to what other major compilers do.
In this specific case, I think the problem is that ... |
74,668,614 | 74,668,742 | CMake `add_executable` and `target_link_libraries` throwing linking error | I am following Asio tutorial by javidx9 and using CMake to link my executables and libraries. Complete source code is available in this repository.
I am facing a linking error with the executables Server.cpp and Client.cpp in folder
- Source
---- Main
-------- Server.cpp
-------- Client.cpp
In the main function if I c... | You have template ServerInterface<CustomMessageTypes> implemented in a source file. Either move the implementation to a header, which is usually what you do, or provide the symbol ServerInterface<CustomMessageTypes> by explicitly instantianting the template in source file. See Why can templates only be implemented in t... |
74,668,665 | 74,670,891 | Visitor Pattern with Templated Visitor | This is a follow up on No user defined conversion when using standard variants and visitor pattern
I need to implement a templated version of the visitor pattern as shown below, however it looks like the accept function has to be virtual which is not possible. Could you please help me?
#include <variant>
#include <iost... | It says in the question that Visitable cannot be a template. But is it allowed to inherit from a template class? And do you know all the possible visitors? If so, you could add a new template class that Visitable inherits from and that declares virtual methods for all the visitors:
template <typename ... T> class Accep... |
74,669,232 | 74,669,485 | how to solve error ( functions containing switch are not expanded inline ) in C++ | #include<iostream.h>
#include<conio.h>
class hostel_mangt
{
public:
int x,h,id,rc,hd;
char name[15],dol[10];
void oprt_1()
{
cout<<"do u want to see or update room's ?"<<endl;
cout<<"enter 1 to see and 0 to do operations = "<<endl;
cin>>h;
}
void display... | You have a bunch of syntax errors.
Missing closing brace for the if (h == 1) statement.
Misplaced semicolon for the cout<<"what do u want to update ? ";<<endl line (it should be at the end)
Missing closing brace for the outermost else statement in the display_1() function.
Missing closing brace for display_1().
Missin... |
74,669,570 | 74,669,621 | Is there any standard variadic function for erasing multiple elements in a vector? | Take this vector:
std::vector<int> v = {1, 2, 3, 4, 5};
Let's say I want to remove some elements of a vector at some arbitrary indices: 0, 1, and 3. It's tedious to have to write something like this:
v.erase(v.begin());
v.erase(v.begin());
v.erase(v.begin() + 1);
Is there any standard function that takes in an arbitr... | Yes and no.
There's nothing that deals with indices. There's also nothing that deals with arbitrary elements.
But you can erase multiple items that form a contiguous range at once. So you can coalesce your first two calls to erase into one (and probably about double the speed in the process).
// erase the first two ele... |
74,669,769 | 74,669,812 | How can I get numbers from number (like this : 731===>[7,3,1]) with recursive function | Here I can use down method to do this
Get a whole number (192)============> (1,9,2)
#include <iostream> // I Know This way
using namespace std;
int argam(int n);
int main()
{
int a;
cout << "Please enter num : ";
cin >> a;
argam(a);
}
int argam(int n)
{
do
{
cout << n % 10 << "\n";
... | It's even shorter when done recursively:
void argam(int n)
{
if (n == 0) return; // end condition for the recursion
cout << n % 10 << "\n"; // print 1 digit
argam(n / 10); // call the same function again without that digit
}
|
74,669,777 | 74,670,605 | C++ Client-server (FIFOs, pipes, forks) | I' ll attach here the code I wrote, it doesn't work the way it should, it doesn't read properly from fifo. It was sending the username correctly before adding more code, it makes me think I wrote the code bad from beginning. If it's helpful I'll post the client code too, but I think the problem is here. When I run the ... | A few issues ...
Doing printf for debug can interfere with the pipe data. Better to use stderr. A macro (e.g. prte and dbgprt) can help
In copyUsername, doing char *&username is overly complicated. It can/should be char *username.
Also, doing int &length is also complicated. Just pass back length as a return value.
In... |
74,670,025 | 74,670,087 | C++: Question on access specifier in inheritance | Here's the following code.
#include <iostream>
using namespace std;
class B {
private:
int a=1;
protected:
int b=2;
public:
int c=3;
};
class D : protected B { // clause 1
};
class D2 : public D { // clause 2
void x() {
c=2;
}
};
int main() {
D d;
D2 d2;
... | The type of inheritance you use does not affect the protection level of members in the parent class. It only changes the protection level of those members in the child class.
When you define class D : protected B it is equivalent to defining class D like this:
class D
{
protected:
int b=2;
int c=3;
};
Then when yo... |
74,671,017 | 74,671,035 | Creating a bookingsystem in C++ | The following two are not an overlap since they do not share the same reference Id:
Reservation foo("Bastuflotta", Date(1, 1, 2022), Date(5, 1, 2022));
Reservation bar("Badtunna", Date(3, 1, 2022), Date(8, 1, 2022));
foo.Overlaps(bar); // returns false
I have tried and tried but can't get Overlaps to work. Pls if y... | To implement the Overlaps function, you can check if the start or end date of the given Reservation object (other) falls between the start and end dates of the current Reservation object (this), or if the start or end date of the current Reservation object falls between the start and end dates of the given Reservation ... |
74,671,173 | 74,671,197 | Copy constructor difference for std::unique_ptr | If my understanding is correct, the following declarations should both call the copy constructor of T which takes type of x as a parameter.
T t = x;
T t(x);
But when I do the same for std::unique_ptr<int> I get an error with the first declaration, while the second compiles and does what is expected.
std::unique_ptr<in... | Constructor of std::unique_ptr<> is explicit, which means, you need to write it in the first case:
std::unique_ptr<int> x = std::unique_ptr<int>(new int());
// or
auto x = std::unique_ptr<int>(new int());
// or make_unique()
|
74,671,304 | 74,672,155 | Boost::multiprecision and cardinal_cubic_b_spline | I'm new using the boost::multiprecision library and tried to use it combination with boost::math::interpolators::cardinal_cubic_b_spline however I can't compile the program.
The example code is
#include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>
#include <iostream>
#include <boost/multiprecision/gmp.hpp>
u... | The selected type. is the GMP backend. To give it the usual operators, it is wrapped in the frontend template number<>:
Live On Coliru
using F = boost::multiprecision::mpf_float_50;
int main() {
F a = 3, b = 2;
F c = b - a;
std::cout << "a:" << a << ", b:" << b << ", c:" << c << std::endl;
b = abs(b -... |
74,671,392 | 74,671,410 | Prevent a function which executes itself after 1 second from being executed every 1 second one by one in a for loop | I have a function which makes players die after 1 second. But if I have 2 players, first player will die after 1 second and then the second will die in 1 second. I want them both to die in the same time in the first second (together)
dieAfter1Second() {
for (int players = 0; players < maxPlayers; players ++) {
... | One way to execute the function for all players in the same time would be to use a timer, such as std::chrono::steady_clock. This would allow you to wait for 1 second before calling the function for each player.
Here is an example of how you could do this:
#include <chrono> // for std::chrono::steady_clock
#include <io... |
74,671,783 | 74,671,798 | How to inherit using declarations from base class | I declare types within class Config, pass this to base class Parent so Child can access.
The idea is each Child (there are many) won't have to keep declaring it's own using declarations, because they are already in Parent.
However, this doesn't compile. Child cannot see Parent::Type.
Is it possible to achieve this some... | These are automatically inherited, but not visible. The reason these are not visible is, template base class is not considered during name lookup. It's not specific to types, same occurs with member variables. If you want them to be accessible, you need to bring them in scope:
struct Child : public Parent<CONFIG>
{
... |
74,672,456 | 74,673,491 | Isn't a quad always composed of 4 vertex? | I'm getting into OpenGL. I'm following learnopengl.com and I reached the text rendering part, where I read (at the end of In Practice > Text Rendering > Shaders section)
The 2D quad requires 6 vertices of 4 floats each, so we reserve 6 * 4 floats of memory. Because we'll be updating the content of the VBO's memory qui... | If a quad contains 2 triangles it can take 6 vertices, 2 vertices will be the duplicated in this case.
Alternatively, you can use 4 vertices and GL_TRIANGLE_STRIP. All vertices will be unique, no duplicates.
Alternatively, there is a trick with only one triangle, 3 vertices only. Vertex shader would look like:
out vec2... |
74,672,502 | 74,672,579 | asio tcp server hanging | I know this is probably a really simple problem but ive been trying to get the asio examples to work correctly for over a week now. whenever I run the program, the terminal hangs and dosent print anything and dosent send any info to the client. Im using Ubuntu Linux and a basic compiler command
g++ main.cpp -o main.exe... |
the terminal hangs and dosent print anything and dosent send any info to the client
You need to connect a client first, because the first thing you do is a blocking accept which never completes unless a connection arrives.
I've compiled your program (with minor modification for Boost Asio):
Live On Coliru
//#define A... |
74,672,781 | 74,672,787 | Why even i am instantiating template parameter at runtime but i am getting expected output instead of error ie. we cannot expand template at runtime? | As I know that templates are expanded at compile time but in below example i am deciding or doing
template instantiation at runtime depending on user input but still i am getting expected output.how this running?
can someone explain me
#include <iostream>
using namespace std;
template<typename T>
class Demo
{
T Val... | At compile time, both templates are created. There exists code in your compiled program for both branches. At runtime you are simply selecting which branch to execute.
The compiler sees the two branches of code and realizes that it cannot determine which branch will be taken at compile time, so it will generate code fo... |
74,673,662 | 74,673,934 | Two programs are same but one is showing error | I have two programs.
1:
#include <iostream>
using namespace std;
int main () {
do {
cout<<"Hello world";
char yn='y';
} while (yn=='y' || yn=='Y');
return 0;
}
2:
#include <iostream>
using namespace std;
int main () {
char yn='y';
do {
cout<<"Hello world";... | The code is not the same. When you declare a variable between {...} it is in scope only between the braces and in this case not in scope in the while condition.
The error is confused by the fact that a different symbol yn (a function) happens to be in scope through indirect inclusion of <cmath> by <iostream> and the i... |
74,673,694 | 74,673,813 | Why does my code return nothing and stops returning anything? | This is part of my homework and I am having difficulty understanding why the output is empty and then the code ends. I don't really understand the class pointer so it would help a lot if there is an explanation of how the class pointer affects the code. Why can I call employee_name using secretary and receptionist but ... | Your problem is that you are not initialising or testing your pointers before you use them.
First you should set both pointers when you construct your department object (this doesn't happen automatically).
Department::Department(std::string n, Employee* s, Employee* r)
{
department_name = n;
secretary = s;
... |
74,675,080 | 74,675,125 | When writing a C++, if the source file is being saved, compile it | I have this question : when I save a C++ source file in VsCode, I always need to run a task through this command, then : this one, translated to English would be : "Compile this C++ active file using g++ compiler". I would like to know if there was a way to make sure that if the file is saved it will be also compiled. ... | EDIT: Sorry, my old approach didn't work and I noticed when re-reading the task.
In order to automatically run the build task when a file is saved, you should use the "file_watcher" (instead of my previous implemention) setting in the .vscode/settings.json file:
{
"files.autoSave": "afterDelay",
"files.watcherExclu... |
74,675,119 | 74,675,499 | Cmake build error on Fedora 37 ; cannot find UDev library | I was trying to make some games in SFML, download the source code on github but i have some dependencies issues while trying to build the code.
enter image description here
I'm working on Fedora 37.
Anyone know how to solve it ?
The library exit on /usr/lib/udev so i guess it's a path issues but i already try to export... | There is no reason to build SFML on Fedora since it is in the repos. Just do
dnf install SFML SFML-devel
|
74,675,402 | 74,675,723 | Writing to the stream buffer of a string stream overrides the previous data | What I want to do is to create string stream , and output stream, giving the buffer of string stream to output stream, so that it will output data to the string stream. Everything seems fine, but when I try to add data to buffer of the string stream it overrides the previous data. My question is why? and how can... | The reason that the string in the stringstream object is being overwritten when you write to it using the ostream object is that, by default, the ostream object writes to the beginning of the stream buffer. This means that when you write the string "hey" to the ostream object, it replaces the initial string in the stri... |
74,677,598 | 74,677,658 | Data types int and double in calculating e | Why, when I use double i the output is (an approximation to) the value of e?
#include <iostream>
using namespace std;
int main ()
{
double s=0;
double i=1;
for (int m=1;m<5;m++)
{
i=m*i;
s=s+1/i;
}
cout<<s+1;
return 0;
}
But when I use int i, the output is 2:
#include <iostr... | The reason that the output is different when you use double or int for the i variable is because of the way that division works in C++. When you use integer division, the result of the division is also an integer. So, in the second example where i is an int, each time you perform the division 1/i, the result is always ... |
74,679,162 | 74,679,482 | Casting `std::unique_ptr` | Is there any problem in performing dynamic casting via the following function?
template<typename Base, typename Derived>
requires std::is_convertible_v<Derived&, Base&> &&
std::is_polymorphic_v<Base>
inline std::unique_ptr<Derived> cast_to(std::unique_ptr<Base>&& ptr)
{
return std::unique_ptr<Deriv... | Yes, your function can easily leak memory if the cast fails. Consider the following:
struct Base
{
virtual ~Base() = default;
};
struct Derived1 : Base {};
struct Derived2 : Base {};
int main()
{
std::unique_ptr<Base> bp = std::make_unique<Derived1>();
// bp does not point to a Derived2, so this cast wi... |
74,679,452 | 74,679,535 | Accessing variable template using decltype | A minimized example of my code showing the problem:
#include <cassert>
#include <iostream>
#include <map>
#include <string>
template <typename T>
const std::map<std::string, T> smap;
template <>
const std::map<std::string, bool> smap<bool>{{"a", false}};
int main() {
std::map<bool, std::string> rmap{{false, "x"}... | decltype(key) is const bool, not bool. And typeid strips const qualifiers, so the two have the same (runtime) representation.
If the type of type or expression is cv-qualified, the result of the typeid refers to a std::type_info object representing the cv-unqualified type (that is, typeid(const T) == typeid(T)).
So w... |
74,680,179 | 74,680,304 | Temporary string comparison with > and < operators in C++ | These operators do not perform lexicographical comparisons and seem to provide inconsistent results.
#include <iostream>
int main () {
std::cout << ("70" < "60") << '\n';
std::cout << ("60" < "70") << '\n';
return 0;
}
and
#include <iostream>
int main() {
std::cout << ("60" < "70") << '\n';
std::c... | Character literals are character arrays. You are comparing these arrays, which after array-to-pointer decay means you are comparing the addresses of the first byte of these arrays.
Each character literal may refer to a different such array, even if it has the same value. And there is no guarantee about the order of the... |
74,680,489 | 74,680,581 | How do I get the unix timestamp as a variable in C++? | I am trying to make an accurate program that tells you the time, but I can't get the current Unix timestamp. Is there any way I can get the timestamp?
I tried using int time = std::chrono::steady_clock::now(); but that gives me an error, saying that 'std::chrono' has not been declared. By the way, I'm new to C++
Let me... | Try using std::time, it should be available in Dev C++ 5.11, but let me know if it also throws an error:
#include <iostream>
#include <ctime>
#include <cstddef> // Include the NULL macro
int main() {
// Get the current time in seconds
time_t now = std::time(NULL);
// Convert the Unix timestamp to a tm str... |
74,680,998 | 74,681,340 | What is a Simple Example for using the Boost Graph Library | I am trying to use the BGL, I find the documentation precise but lacks more examples for simple cases. My goal is described below (after reading the documentation I still couldn't do this):
struct Vertex
{
double m_d;
std::size_t m_id;
};
//or
struct Vertex
{
double m_d;
std::size_t id() const;
};
Go... |
A directed graph G
Straight-away:
struct Vertex {
double m_d = 0;
size_t m_id = -1;
// or std::size_t id() const;
};
struct Edge {
double cost = 0;
};
using Graph =
boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, Vertex, Edge>;
(what is the difference between a bidire... |
74,681,127 | 74,681,158 | Non-const member reference is mutable on const object? | Given the following:
struct S
{
int x;
int& y;
};
int main()
{
int i = 6;
const S s{5, i}; // (1)
// s.x = 10; // (2)
s.y = 99; // (3)
}
Why is (3) allowed when s is const?
(2) produces a compiler error, which is expected. I'd expect (3) to result in a compiler error as well.
|
Why is s.y = 99 allowed when s is const?
The type of s.y for const S s is not int const& but int&. It is not a reference to a const int, but a const reference to an int. Of course, all references are constant, you cannot rebind a reference.
What if you wanted a type S' for which const object cannot be used to change ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.