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,
int line) {
if (err != cudaSuccess) {
printf("%s in %s at line %d\n", cudaGetErrorString(err),
file, line);
exit(EXIT_FAILURE);
}
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))
__global__ void countPrimeGPU(const int* array, int* count)
{
int number = array[threadIdx.x + blockIdx.x * blockDim.x];
if (number <= 1)
return;
for (int i = 2; i <= floor(pow(number, 0.5)); i++)
if (!(number % i))
return;
atomicAdd(count, 1);
}
int main()
{
int* host_array;
int* dev_array;
const int size = 9; // prime numbers from 1-9
// allocating & initializing host array
host_array = new int[size];
for (int i = 0; i < size; i++)
host_array[i] = i + 1; // 1, 2, ..., size
int host_primeCount = 0;
int* dev_pprimeCount;
HANDLE_ERROR(cudaSetDevice(0));
HANDLE_ERROR(cudaMalloc((void**)&dev_array, size * sizeof(int)));
HANDLE_ERROR(cudaMemcpy(dev_array, host_array, size * sizeof(int), cudaMemcpyHostToDevice));
HANDLE_ERROR(cudaMalloc((void**)&dev_pprimeCount, sizeof(int)));
HANDLE_ERROR(cudaMemcpy(dev_pprimeCount, &host_primeCount, sizeof(int), cudaMemcpyHostToDevice));
countPrimeGPU <<< size, 1 >>> (dev_array, dev_pprimeCount); // !!!
HANDLE_ERROR(cudaGetLastError());
HANDLE_ERROR(cudaDeviceSynchronize());
HANDLE_ERROR(cudaMemcpy(&host_primeCount, dev_pprimeCount, sizeof(int), cudaMemcpyDeviceToHost));
printf("Prime count for the first %d numbers: %d\n", size, host_primeCount);
cudaFree(dev_array);
cudaFree(dev_pprimeCount);
HANDLE_ERROR(cudaDeviceReset());
delete[] host_array;
return 0;
}
The problem here is that I get correct result only when size is in interval [1-8]. But, when setting it to 9 or above it is always incorrect. What am I doing wrong? I suspect I have incorrectly set the configuration (number of blocks/threads) when calling countPrimeGPU, but was unable to fix it. Ultimately, I would like to test it with size=10'000'000, and compare it with my multi-threaded CPU implementation. Thank you.
|
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 might have a workable path using ordinary rounding rather than truncation (since testing against a factor slightly larger than the square root is not going to disrupt the correctness of your approach), but the method I would suggest to address this is to change your for-loop as follows:
for (int i = 2; (i*i) <= number; i++)
This avoids the floating-point head scratching, and should be computationally simpler as well. For your desired range of number (up to 10,000,000) the quantity i*i will fit in a int type/value, so I don't forsee issues there.
Since this is just a learning exercise, I'm not trying to scrub your code for all sorts of optimization improvements. To pick one example, launching blocks of 1 thread each:
countPrimeGPU <<< size, 1 >>> (dev_array, dev_pprimeCount); // !!!
is not particularly efficient on the GPU, but it is not algorithmically incorrect to do so.
|
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 can do to help communicate what I am doing, I used getch(); which I am pretty sure my teacher would not like since it isn't standard.
I've tried cin.peek and cin.get but if there is nothing in the stream it always waits for enter which I don't want happening.
I found getch(); and it basically bypasses the problem I am having. I need to make this program operate the same way but using something that is in the c++ standard. Hitting enter after every entry is fine, but I need to detect an empty line and then go into a state where I can detect another one. If it detects one empty line I need to be able to resume entering values.
Here is a somewhat working version with getch(); of what I am going for.
#include <iostream>
#include <conio.h>
using std::cin;
using std::cout;
using std::endl;
const int ARRAY = 500;
int GetUserArray(int b[ARRAY]);
void DisplayVals(int ArrayofValues[ARRAY], int &x);
void SortArray(int ArrayofValues[ARRAY], int& x);
int main()
{
int UserArray[ARRAY]= {0};
int NumberofValues = 0;
//User Populates Array, catches number of entries with return
NumberofValues = GetUserArray(UserArray);
//Displays the NON-SORTED array
DisplayVals(UserArray, NumberofValues);
//Sorts Array
SortArray(UserArray, NumberofValues);
//Displays the SORTED array
DisplayVals(UserArray, NumberofValues);
return 0;
}
int GetUserArray(int UserArray[ARRAY])
{
int howmany = 0;
int input = 0;
//ASCII code for enter key is 13 '\n'
int x = 0;
cout << "Please enter an integer values: ";
for (int i = 0; i < ARRAY; i++)
{
input = _getche();
if (input == 13)
{
cout << endl;
cout << "Please enter an integer value: ";
input = _getche();
if (input == 13)
{
i += 499;
cout << endl;
cout << endl;
cout << "Exiting...";
}
}
UserArray[i] = input;
howmany++;
}
return howmany;
}
void DisplayVals(int ArrayofValues[ARRAY], int &x)
{
cout << '\n' << endl;
for (int i = 0; i < x ; i++)
{
char Display = 0;
Display = ArrayofValues[i];
cout << Display << ' ';
}
cout << endl;
}
void SortArray(int ArrayofValues[ARRAY], int& x)
{
bool sorted = false;
for (int pass = 0; pass < x; pass++)
{
for (int i = 1; i < (x - pass - 1); i++)
{
if ((ArrayofValues[i - 1]) < ArrayofValues[i])
{
int temp = ArrayofValues[i - 1];
ArrayofValues[i - 1] = ArrayofValues[i];
ArrayofValues[i] = temp;
}
}
}
}
|
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 input
if(input==10){
if(exit_flag){
i+=ARRAY; // You should not hard-code any values.
cout<<"Exiting";
}
exit_flag = 1;
--i; //If you don't want to skip an index in case of Single Enter.
continue;
}
else{
exit_flag=0;
UserArray[i] = input-'0'; //Converting ASCII to INT.
howmany++;
cin.ignore(); //Clearing the input buffer as we have pressed 'Enter'.
}
}
return howmany;
}
Thank you.
|
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 B
{
public:
A a;
void test()
{
A a1(6);
a = a1;
}
};
int main()
{
B b1;
b1.test();
return 0;
}
I tried to initialized value in constructor in class and this worked but what if i don't want to do this?
|
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 implicitly delete'd.
Thus, b1 in main() can't be default-constructed, either.
If you want A to be default-constructible, you need to either:
add a default constructor explicitly:
class A
{
public:
int a = 0;
A() {}; // or: A() = default; // <-- HERE
A(int _a) : a(_a) {}
};
Change your converting constructor so it can also act as a default constructor:
class A
{
public:
int a = 0;
A(int _a = 0) : a(_a) {} // <-- HERE
};
Otherwise, you will have to add a default constructor to B to construct B::a with a value:
class B
{
public:
A a;
B() : a(0) {} // <-- HERE
void test()
{
A a1(6);
a = a1;
}
};
|
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;
while(i <= mid && j <= end){
if(arr[i] <= arr[j]){
arrB[k] = arr[i];
k++;
i++;
}
else {
arrB[k] = arr[j];
k++;
j++;
}
}
while(i <= mid){
arrB[k] = arr[i];
i++;
k++;
}
while(j <= end){
arrB[k] = arr[j];
j++;
k++;
}
k = 0;
for(int i = begin; i <= end; i++){
arr[i] = arrB[k];
s.setData(arr);
k++;
}
delete[] arrB; //error here
}
I've tried replacing <= to < for n-1, I've tried switching to vectors and that also gives me an error. I've also tried looking at similar questions.
|
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] <= arr[j]) {
arrB[k] = arr[i];
i++;
} else {
arrB[k] = arr[j];
j++;
}
// Increment the k variable after each element is added to arrB
k++;
}
while (i <= mid) {
arrB[k] = arr[i];
i++;
k++;
}
while (j <= end) {
arrB[k] = arr[j];
j++;
k++;
}
// Call the setData method once, outside of the for loop
s.setData(arr);
k = 0;
for (int i = begin; i <= end; i++) {
arr[i] = arrB[k];
k++;
}
}
|
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){ return v * 2; })
| std::ranges::to<std::vector>();
static_assert(std::same_as<decltype(vec), std::vector<int>>);
std::ranges::for_each(vec, [](auto const v){ std::cout << v << ' '; });
}
But getting a error
main.cpp: In function 'int main()':
main.cpp:11:29: error: 'to' is not a member of 'std::ranges'
11 | | std::ranges::to<std::vector>();
| ^~
main.cpp:11:43: error: missing template arguments before '>' token
11 | | std::ranges::to<std::vector>();
| ^
main.cpp:11:45: error: expected primary-expression before ')' token
11 | | std::ranges::to<std::vector>();
| ^
main.cpp:13:24: error: template argument 1 is invalid
13 | static_assert(std::same_as<decltype(vec), std::vector<int>>);
https://coliru.stacked-crooked.com/view?id=8fdd3554af82ef24
I am using the compiler C++23
|
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::to()
P1206R7
|
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;
int n = word1.size();
vector<int>freq1(26,0);
vector<int>freq2(26,0);
for(int i= 0 ; i < n ; ++i){
freq1[word1[i]-'a']++;
freq2[word2[i]-'a']++;
}
sort(freq1.rbegin(),freq1.rend());
sort(freq2.rbegin(),freq2.rend());
**if(set(word1.begin(),word1.end())!=set(word2.begin(),word2.end()))**
return false;
for(int i= 0;i<26;++i){
if(freq1[i]!=freq2[i])
return false;
}
return true;
}
};
I am not understanding what does set(word1.begin(),word1.end()) mean over here, I tried to search on the internet for answer but I didn't got any satisfying answer, if someone can explain it would be very helpful. Thanks in advance!
|
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 "dog" and "good" would.
So, this code is saying that if the words do not share all of the same letters, then they would not be considered close.
|
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;
size_t read, write;
write = fwrite(&value, sizeof(value), 1, file);
fseek(file, 0, SEEK_SET);
read = fread(&retrieved, sizeof(value), 1, file);
return true;
}
int main(int argc, char *argv[]) {
FILE *file = NULL;
file = fopen("file_test", "wb+");
file_read(file);
fclose(file);
}
I checked if file is opened correctly and that retrieved has the same value as value. I don't think I'm freeing any variables in my code. I'm suspecting that fread is causing all the trouble.
fread(&retrieved[0], sizeof(char), 4, file)
Doesn't read the value to retrieved and was where I am doing wrong.
|
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 ifstream
|
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
#include <iostream>
#include <regex>
int main()
{
std::string temporary_recieve_data = " S S +456.789 tg\r\n";
std::string::size_type sz;
const std::regex reg_exp("\\D|[^+-.]"); // matches not digit, decimal point (.), plus sign, minus sign
std::string numeric_string = std::regex_replace(temporary_recieve_data, reg_exp, ""); //replace the character that are not digit, dot (.), plus-minus sign (+,-) with empty character/string for float conversion
std::cout << "Numeric String : " << numeric_string << std::endl;
if (numeric_string.empty())
{
return 0;
}
float data_value = std::stof(numeric_string, &sz);
std::cout << "Float Value : " << data_value << std::endl;
return 0;
}
I have been trying to evaluate my regex expression on regex101.com for past 2 days but I am unable to figure out where I am wrong with my regular expression. When I just put \D, the editor substitutes non-digit character properly but soon as I add or condition | for not dot . or plus + or minus - sign the editor returns empty string.
|
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 the start or end of the char-class.
(funnily the used range +-. 43-46 even contained a hyphen)
Remove the alternation with \D and put \d into the negated class:
[^\d.+-]+
See this demo at regex101 (attaching + for one or more is efficient)
|
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 not compile, with: error: cannot bind rvalue reference of type 'int&&' to lvalue of type 'int'.
I understand the error. A fix would be to give it an rvalue like so:
MyTemplateClass<int> Instance{ 5 };
But this isn't very usable. I could also give it a more specific type:
MyTemplateClass<const int&> Instance{ x };
But I feel like this could be better. For instance, std::vector can do:
int x = 5;
std::vector<int>{ x, x, x };
This works just fine... how does std::vector accomplish this? Is there something wrong with my code?
Thank you.
|
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 T>
MyTemplateClass(T&& Value) : MyMemberVar{ std::forward<T>(Value) } {}
Demo
|
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 return 0 and the effect of them. Additionally, why not use void type?
|
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 function will return 0 to indicate that the operation has failed. Otherwise, the function will insert the new element, increment the length of the list, and return 1 to indicate that the operation has succeeded.
The use of return statements in this way is a common pattern in programming, as it allows the calling code to determine whether an operation has succeeded or failed. In this case, the calling code can check the return value of the InsertElem() function and take appropriate action based on the result.
As for why the InsertElem() function doesn't use the void type, it is because the function is expected to return a value indicating the success or failure of the operation. The void type is used to indicate that a function does not return a value, so it would not be appropriate to use it in this case. Instead, the function uses the int type to indicate that it will return an integer value.
|
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:
alpaca::Config* config;
public:
Client();
string connect();
};
}
The implementation in alpaca/client.cpp is
#include <iostream>
#include <string>
#include <client.h>
#include <httplib.h>
using namespace std;
namespace alpaca {
Client::Client() {
config = &alpaca::Config();
};
string Client::connect() {
httplib::Client client(config->get_url(MARKET));
auto res = client.Get("/v2/account");
if (res) {
return res->body;
}
else {
return "Error in Client::get_account(): " + to_string(res->status);
}
};
}
And my main.cpp is:
#include <iostream>
#include <string>
#include <client.h>
using namespace std;
int main()
{
alpaca::Client client = alpaca::Client();
client.connect();
return 0;
}
However, I see the following error when I try to compile with g++:
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\shubh\AppData\Local\Temp\cc765kwL.o:main.cpp:(.text+0x1ca): undefined reference to 'alpaca::Client::Client()'
Could anyone help with what exactly I'm missing? I'm not too sure.
The g++ command I use is g++ -I./src/alpaca src/main.cpp
|
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 genderBoolean is false, then gender is female. I tried to put the if-else statement outside of the struct, but the IDE says
Identifier "genderBoolean" is undefined
which causes another compilation error.
It seems that if-else statement cannot be used within struct in C++. I found out that adding a # before the if statement and adding #endif can solve the compilation error of "expected a declaration" in Microsoft Visual Code 2022, but the output of the program is:
"Name = Mike Gender = Age = 50 Nationality = American"
I expected its output to be :
"Name = Mike Gender = male Age = 50 Nationality = American"
My code also generates compilation message that says the variable genderBoolean is uninitialized, but it can run:
#include <iostream>
using namespace std;
int main() {
struct Person {
string name;
bool genderBoolean;
string gender;
string age;
string nationality;
#if(genderBoolean == true) {
gender = "male";
}
else if (genderBoolean == false) {
gender = "female";
}
#endif
};
Person person1;
person1.name = "Mike";
person1.genderBoolean = true;
person1.age = "50";
person1.nationality = "American";
cout << "Name = " << person1.name << " Gender = " << person1.gender <<
" Age = " << person1.age << " Nationality = " << person1.nationality <<
endl;
return 0;
}
I tried to put the if-else statement outside of the struct but it says identifier "genderBoolean" is undefined.
I expected its output to be :
"Name = Mike Gender = male Age = 50 Nationality = American"
What actually resulted :
"Name = Mike Gender = Age = 50 Nationality = American"
|
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 variables private and providing methods to set them so you can add error checking and preserve invariants like keeping the two gender variables in sync.
I added #include <string> because you should always include what you use and not depend on another file to include it since that may not always be the case and removed using namespace std; because it's a bad habit. Read Why is "using namespace std;" considered bad practice? for more information.
#include <iostream>
#include <string>
enum class Gender
{
Male,
Female
};
struct Person
{
std::string name;
bool genderBoolean;
std::string gender;
std::string age;
std::string nationality;
Person(const std::string& name, Gender genderType,
const std::string& age, const std::string& nationality)
: name(name)
, genderBoolean(genderType == Gender::Male)
// A way to initialize the gender
, gender(genderType == Gender::Male ? "male" : "female")
, age(age)
, nationality(nationality)
{
// A way to assign the gender
// If you use this remove the one above
// You don't need both
//if (genderBoolean)
//{
// gender = "male";
//}
//else
//{
// gender = "female";
//}
}
void setGender(Gender genderType)
{
// A way to change the gender
// Would be best if the member variables were private
// But would not prevent the class from making them mismatch
// by modifying the gender variable directly
if (genderType == Gender::Male)
{
gender = "male";
}
else
{
gender = "female";
}
}
friend std::ostream& operator<<(std::ostream& out, const Person& p);
};
std::ostream& operator<<(std::ostream& out, const Person& p)
{
out << "Name = " << p.name
<< ", Gender = " << p.gender
<< ", Age = " << p.age
<< ", Nationality = " << p.nationality
<< "\n";
return out;
}
int main()
{
Person person1("Mike", Gender::Male, "50", "American");
std::cout << person1;
person1.setGender(Gender::Female);
std::cout << person1;
return 0;
}
Demo
Output:
Name = Mike, Gender = male, Age = 50, Nationality = American
Name = Mike, Gender = female, Age = 50, Nationality = American
|
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::accumulate( group, 1ll, ranges::multiplies() );
}
int64_t calculateGroupSum( const std::vector<int>& data ) {
using ranges::views::transform;
using ranges::views::chunk;
return ranges::accumulate(
data
| chunk( 3 )
| transform( [] ( auto group ) { return getGroupValue( group ); })
, 0ll);
}
I want to do the following:
int64_t calculateGroupSum( const std::vector<int>& data ) {
using ranges::views::transform;
using ranges::views::chunk;
return ranges::accumulate(
data
| chunk( 3 )
| transform( getGroupValue )
, 0ll);
}
Is this somehow possible by using a different parameter type for getGroupValue() or do I have to use the lambda?
|
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() );
}
} getGroupValue;
*it can work if the parameter has specific type, but it's not the case for range::views::transform
|
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>
#include <thread>
#include <vector>
#include <random>
#include <chrono>
using Clock = std::chrono::high_resolution_clock;
namespace Vars
{
const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device
const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread
std::vector<int> RandNums(NumPerThread*N);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 1000);
int sz = 0;
}
using namespace Vars;
void AddN(int start)
{
static std::mutex mtx;
std::lock_guard<std::mutex> lock(mtx);
for (unsigned int i=start; i<start+NumPerThread; i++)
{
RandNums[i] = dis(gen);
++sz;
}
}
int main()
{
auto start_time = Clock::now();
std::vector<std::thread> threads;
threads.reserve(N);
for (unsigned int i=0; i<N; i++)
{
threads.emplace_back(std::move(std::thread(AddN, i*NumPerThread)));
}
for (auto &i: threads)
{
i.join();
}
auto end_time = Clock::now();
std::cout << "\nTime difference = "
<< std::chrono::duration<double, std::nano>(end_time - start_time).count() << " nanoseconds\n";
std::cout << "size = " << sz << '\n';
}
and a single-threaded version
#include <iostream>
#include <thread>
#include <vector>
#include <random>
#include <chrono>
using Clock = std::chrono::high_resolution_clock;
namespace Vars
{
const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device
const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread
std::vector<int> RandNums(NumPerThread*N);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 1000);
int sz = 0;
}
using namespace Vars;
void AddN()
{
for (unsigned int i=0; i<NumPerThread*N; i++)
{
RandNums[i] = dis(gen);
++sz;
}
}
int main()
{
auto start_time = Clock::now();
AddN();
auto end_time = Clock::now();
std::cout << "\nTime difference = "
<< std::chrono::duration<double, std::nano>(end_time - start_time).count() << " nanoseconds\n";
std::cout << "size = " << sz << '\n';
}
The execution times are more or less the same. I am assuming there is a problem with the multi-threaded version?
P.S. I looked at all of the other similar questions here, I don't see how they directly apply to this task...
|
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 each thread has its own copy of
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 1000);
That should run much faster.
UNTESTED code - but this should make my above suggestion more clear:
using Clock = std::chrono::high_resolution_clock;
namespace SharedVars
{
const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device
const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread
std::vector<int> RandNums(NumPerThread*N);
std::mutex mtx;
}
void PerThread_AddN(int threadNumber)
{
using namespace SharedVars;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 1000);
int sz = 0;
vector<int>::iterator from;
vector<int>::iterator to;
{
std::lock_guard<std::mutex> lock(mtx); // hold the lock only while accessing shared vector, not while accessing its contents
from = RandNums.begin () + threadNumber*NumPerThread;
to = from + NumPerThread;
}
for (auto i = from; i < to; ++i)
{
*i = dis(gen);
}
}
int main()
{
auto start_time = Clock::now();
std::vector<std::thread> threads;
threads.reserve(N);
for (unsigned int i=0; i<N; i++)
{
threads.emplace_back(std::move(std::thread(PerThread_AddN, i)));
}
for (auto &i: threads)
{
i.join();
}
auto end_time = Clock::now();
std::cout << "\nTime difference = "
<< std::chrono::duration<double, std::nano>(end_time - start_time).count() << " nanoseconds\n";
std::cout << "size = " << sz << '\n';
}
|
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;
fs.open("test_text.txt");
if(!fs.is_open()){
cout << "could not open file" << endl;
}
map <string, int> mp;
string word;
while(fs >> word){
for(int i = 0; i < word.length(); i++){
if(ispunct(word[i])){
word.erase(i--, 1);
}
}
if(mp.find(word) != mp.end()){
mp[word]++;
}
}
vector <pair <string, int> > v(mp.size());
copy(mp.begin(), mp.end(), v.begin());
return 0;
}
|
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 std::transform.
|
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 choice of how many rows to delete.
Delete data in the selected row.
Display the entire contents of the file.
I have created the program as below:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// Function Prototipe
void garis();
void show_databefore();
void show_data();
void del_line(const char *file_name, int n);
// Variable Declaration
int n;
ifstream myFile;
string output,buffer;
// Main Function
int main(){
cout << "Show data and delete specific line Program " << endl;
garis ();
cout << "The Data " << endl;
show_databefore();
garis();
cout << "Select the Rows of data you want to delete: ";
cin >> n;
cout << "\nBefore " << endl;
// If Case after input n
if((0 < n) && (n < 100)){
del_line("data1.txt", n); // this process will delete the row that has been selected.
} else {
cout << "Error" << endl;}
show_data(); // when calling this function. Display on the console, data is displayed 2 times.
return 0;
}
//Function to delete data in the row that has been selected
void del_line(const char *file_name, int n){
ifstream fin(file_name);
ofstream fout;
fout.open("temp.txt", ios::out);
char ch;
int line = 1;
while(fin.get(ch))
{
if(ch == '\n')
line++;
if(line != n)
fout<<ch;
}
fout.close();
fin.close();
remove(file_name);
rename("temp.txt", file_name);
}
// Function to display data1.txt to the console
void show_databefore(){
myFile.open("data1.txt");
while (!myFile.eof()){
getline(myFile,buffer);
output.append("\n" + buffer);
}
cout << output << endl;
myFile.close();
}
// Function to display data1.txt to the console T
// This fuction actually same as show_databefore.
void show_data(){
myFile.open("data1.txt");
while (!myFile.eof()){
getline(myFile,buffer);
output.append("\n" + buffer);
}
cout << output;
myFile.close();
}
//Function to provide a boundary line.
void garis(){
cout << "======================================================= " << endl << endl;
}
When I run my program it works, but when I bring up data to the console, my data appears 2 times and I've tried the method without using the function. However, the result remains the same.
Here is the result
Can anyone help me? Or maybe there's an easier way to build my program? Thank you
|
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 variable output. The code assumes that the variable is an empty string when the function is entered, but because it's a global variable there is no way to ensure this. Here's a fixed version, the global variable is now a local variable and the eof problem has been fixed.
void show_data(){
string output; // local variable
myFile.open("data1.txt");
while (getline(myFile,buffer)){
output.append("\n" + buffer);
}
cout << output;
myFile.close();
}
Don't needlessly use global variables, they are a huge source of bugs, as well as many other problems. There are several others in your code. They should all be removed.
|
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 <iostream>
#include <string>
using namespace std;
struct Node{
string item;
Node* next;
Node* prev;
};
struct Queue{
int size;
Node* head = NULL;
Node* tail = NULL;
};
//Makes queue
Queue* createQueue(){
Queue* n = new Queue;
n->head = NULL;
n->tail = NULL;
n->size = 0;
return n;
}
//checks if empty
bool isEmpty(Queue* List){
if( List->size == 0){
return true;
}else{
return false;
}
}
// add item to queue
bool enqueue(Queue* List, string added){
Node* newy= new Node;
if(List->tail == NULL){
List->head = List->tail = newy;
return true;
}
List->tail->next = newy;
List->tail = newy;
List->size++;
return true;
}
//remove item from queue
string dequeue(Queue* List){
Node* tempo = List->head;
if(List->head == NULL){
return "ERROR";
}
else if (tempo->next !=NULL){
tempo = tempo->next;
return List->head->item;
free(List->head);
List->head = tempo;
}else{
return List->head->item;
free(List->head);
List->head= NULL;
List->tail = NULL;
}
}
// display the queue
void print(Queue* List){
Node* yuuur = List->head;
while(yuuur != NULL){
cout<<(yuuur->item)<<endl;
yuuur = yuuur->next;
}
}
// destroy queue
void destroyQueue(Queue* List){
while(List->head !=NULL){
Node *tempo = List->head;
List->head= List->head->next;
delete tempo;
}
List->tail = NULL;
List->head = NULL;
delete List;
}
My main to test the code:
//test code
int main(){
Queue* q = createQueue();
cout << boolalpha << isEmpty(q) << endl;
cout << dequeue(q) << endl;
enqueue(q, "Jos");
enqueue(q ,"An");
enqueue(q, "Peter");
print(q); //Jos, An en Peter worden op drie regels geprint
string first = dequeue(q);
cout << first << endl; //Jos wordt geprint
print(q); //An en Peter worden geprint
destroyQueue(q);
return 0;
}
Valgrind error:
==77== Memcheck, a memory error detector
==77== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==77== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==77== Command: student/labo13
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400DDA: print(Queue*) (in /task/student/labo13)
==77== by 0x401002: main (in /task/student/labo13)
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400DDA: print(Queue*) (in /task/student/labo13)
==77== by 0x40103F: main (in /task/student/labo13)
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400DDA: print(Queue*) (in /task/student/labo13)
==77== by 0x401097: main (in /task/student/labo13)
==77==
==77== Conditional jump or move depends on uninitialised value(s)
==77== at 0x400E23: destroyQueue(Queue*) (in /task/student/labo13)
==77== by 0x4010A3: main (in /task/student/labo13)
==77==
==77==
==77== HEAP SUMMARY:
==77== in use at exit: 0 bytes in 0 blocks
==77== total heap usage: 10 allocs, 10 frees, 263 bytes allocated
==77==
==77== All heap blocks were freed -- no leaks are possible
==77==
==77== For counts of detected and suppressed errors, rerun with: -v
==77== Use --track-origins=yes to see where uninitialised values come from
==77== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 0 from 0)
|
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 tail is not NULL, then you do:
List->tail->next = newy;
List->tail = newy;
List->size++;
return true;
Again, at this point, newy does not have any of its members set.
What you probably want to do is (I didn't try it):
bool enqueue(Queue* List, const string &added){
Node* newy= new Node;
newy->item = added;
newy->next = nullptr;
newy->prev = List->tail;
List->size++;
if(List->tail == nullptr){
List->head = List->tail = newy;
return true;
}
List->tail->next = newy;
List->tail = newy;
return true;
}
On another note, it seems like you are trying to treat C++ like it' C. You should use proper classes and member functions.
|
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 ()
// Rescan macro tokens 256 times
#define EXPAND(arg) EXPAND1(EXPAND1(EXPAND1(EXPAND1(arg))))
#define EXPAND1(arg) EXPAND2(EXPAND2(EXPAND2(EXPAND2(arg))))
#define EXPAND2(arg) EXPAND3(EXPAND3(EXPAND3(EXPAND3(arg))))
#define EXPAND3(arg) EXPAND4(EXPAND4(EXPAND4(EXPAND4(arg))))
#define EXPAND4(arg) arg
#define FOR_EACH(macro, ...) \
__VA_OPT__(EXPAND(FOR_EACH_HELPER(macro, __VA_ARGS__)))
#define FOR_EACH_HELPER(macro, a1, ...) \
macro(a1) \
__VA_OPT__(FOR_EACH_AGAIN PARENS (macro, __VA_ARGS__))
#define FOR_EACH_AGAIN() FOR_EACH_HELPER
#define ENUM_CASE(name) case name: return #name;
#define MAKE_ENUM(type, ...) \
enum type { \
__VA_ARGS__ \
}; \
constexpr const char * \
to_cstring(type _e) \
{ \
using enum type; \
switch (_e) { \
FOR_EACH(ENUM_CASE, __VA_ARGS__) \
default: \
return "unknown"; \
} \
}
MAKE_ENUM(MyType, ZERO, ONE, TWO, THREE);
void
test(MyType e)
{
std::cout << to_cstring(e) << " = " << e << std::endl;
}
int
main()
{
test(ZERO);
test(ONE);
test(TWO);
test(THREE);
}
/*
Local Variables:
c-macro-pre-processor: "c++ -x c++ -std=c++20 -E -"
End:
*/`
I cant figure out for the life of me what the problem is.
I've tried modifying the code, to me it seems that __VA_ARGS__ isn't accepted when it should be, or that it can't accept the way the macros are ordered. Here are the errors:
1>make_enum.cc
1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): warning C4003: not enough arguments for function-like macro invocation 'FOR_EACH_HELPER'
1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): warning C4003: not enough arguments for function-like macro invocation 'ENUM_CASE'
1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2059: syntax error: 'case'
1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2065: 'ENUM_CASE': undeclared identifier
1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C3861: 'FOR_EACH_HELPER': identifier not found
1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2059: syntax error: ')'
1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): error C2146: syntax error: missing ';' before identifier 'default'
1>C:\Users\Thomas\source\repos\outoftouch\outoftouch\make_enum.cc(40,1): warning C4065: switch statement contains 'default' but no 'case' labels
1>Done building project "outoftouch.vcxproj" -- FAILED.
|
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 the old preprocessor incorrectly expands FOR_EACH_AGAIN in FOR_EACH_HELPER early; it shouldn't, because it is not followed by parentheses. Compare the corresponding section "Rescanning replacement list for macros" in the above mentioned article. The warning "not enough arguments for function-like macro invocation 'FOR_EACH_HELPER'" also hints at that.
With /Zc:preprocessor, the code compiles without issues. Example on godbolt.
|
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 create the class object CustomServer which inherits from ServerInterface
int main ()
{
CustomServer server(60000);
return 0;
}
I get following linking error:
Undefined symbols for architecture x86_64:
"Tachys::Networking::ServerInterface<CustomMessageTypes>::ServerInterface(unsigned short)", referenced from:
CustomServer::CustomServer(unsigned short) in Server.cpp.o
"Tachys::Networking::ServerInterface<CustomMessageTypes>::~ServerInterface()", referenced from:
CustomServer::~CustomServer() in Server.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [Source/Main/exe_server] Error 1
make[1]: *** [Source/Main/CMakeFiles/exe_server.dir/all] Error 2
make: *** [all] Error 2
But I have used add_executable in the CMakeList.txt at:
- Source
---- Main
-------- CMakeLists.txt
and target_link_libraries in the main CMakeLists.txt at:
- CMakeLists.txt
It seems like these are the only two functions required to create an executable and link it to a created library but I am still getting this linking error and not able to figure out what to change. Please help.
|
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 the header file? and other endless online resources.
__Start__
Identifiers starting with double underscores are reserved. You are can't use them in your code.
|
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 <iostream>
class Visitable //I need this to be non-templated (no template for Visitable!!): Otherwise I could use CRTP to solve this issue.
{
public:
virtual ~Visitable() = default;
template<typename Visitor>
/*virtual*/ double accept(Visitor* visitor) //I can't do virtual here.
{
throw("I don't want to end up here");
};
protected:
Visitable() = default;
};
struct DoubleVisitable : public Visitable
{
template<typename Visitor>
double accept(Visitor* visitor)
{
return visitor->visit(*this);
};
double m_val = 1.0;
};
struct StringVisitable : public Visitable
{
template<typename Visitor>
double accept(Visitor* visitor)
{
return visitor->visit(*this);
};
double m_val = 0.0;
};
template<typename... args>
class Visitor
{
public:
virtual ~Visitor() = default;
virtual double visit(typename std::variant<args...> visitable)
{
auto op = [this](typename std::variant<args...> visitable) -> double { return this->apply(visitable); };
return std::visit(std::ref(op), visitable);
}
virtual double apply(typename std::variant<args...> visitable) = 0;
Visitor() = default;
};
class SubVisitor : public Visitor<DoubleVisitable, StringVisitable>
{
public:
virtual ~SubVisitor() = default;
SubVisitor() : Visitor<DoubleVisitable, StringVisitable>() {};
virtual double apply(std::variant<DoubleVisitable, StringVisitable> visitable) override
{
return std::visit(
[this](auto&& v){return process(v);},
visitable
);
};
virtual double process(const StringVisitable& visitable)
{
std::cout << "STRING HANDLED" << std::endl;
return 0.0;
}
virtual double process(const DoubleVisitable& visitable)
{
std::cout << "DOUBLE HANDLED" << std::endl;
return 1.0;
}
};
int main(int argc, char* argv[])
{
SubVisitor visitor;
DoubleVisitable visitable;
visitable.accept(&visitor);
//I want to be doing this:
Visitable* doubleV = new DoubleVisitable();
doubleV->accept(&visitor);
delete doubleV;
return 1;
}
The code is here Link. Could you please help me make this not throw but collapses to the right child class DoubleVisitable or StringVisitable. It looks like I need virtual templated member function which is not possible as mentioned here Can a class member function template be virtual?
|
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 AcceptMethods {};
template <> class AcceptMethods<> {};
template <typename First, typename ... Rest>
class AcceptMethods<First, Rest...> : public AcceptMethods<Rest...> {
public:
virtual double accept(First* ) = 0;
virtual ~AcceptMethods() {}
};
typedef AcceptMethods<SubVisitor> AllAcceptMethods;
class Visitable : public AllAcceptMethods
{
public:
virtual ~Visitable() = default;
};
In the above code, we are just listing SubVisitor, but AcceptMethods is variadic so it could be typedef AcceptMethods<A, B, C, D, AndSoOn> AllAcceptMethods;.
Then we add another template class WithGenericAcceptMethod whose purpose is to implement the accept methods declared by AcceptMethods by calling a template method acceptT:
template <typename This, typename ... T> class WithGenericAcceptMethod {};
template <typename This> class WithGenericAcceptMethod<This, AcceptMethods<>> : public Visitable {};
template <typename This, typename First, typename ... Rest>
class WithGenericAcceptMethod<This, AcceptMethods<First, Rest...>> : public WithGenericAcceptMethod<This, AcceptMethods<Rest...>> {
public:
double accept(First* visitor) override {
return ((This*)this)->template acceptT<First>(visitor);
}
virtual ~WithGenericAcceptMethod() {}
};
This class takes as first argument a This parameter in the spirit of CRTP. Then we can now let the specific visitable classes inherit from WithGenericAcceptMethod and implement the template acceptT method:
struct DoubleVisitable : public WithGenericAcceptMethod<DoubleVisitable, AllAcceptMethods>
{
template<typename Visitor>
double acceptT(Visitor* visitor)
{
return visitor->visit(*this);
};
double m_val = 1.0;
};
struct StringVisitable : public WithGenericAcceptMethod<StringVisitable, AllAcceptMethods>
{
template<typename Visitor>
double acceptT(Visitor* visitor)
{
return visitor->visit(*this);
};
double m_val = 0.0;
};
|
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_1()
{
if(h==1)
{
if (name==NULL)
{
cout<<"room is empty "<<endl;
}
else
{
cout<<"id = "<<id<<endl;
cout<<"name = "<<name<<endl;
cout<<"date of leaving = "<<dol<<endl;
}
else
{
cout<<" 1. Update the room member and its data "<<endl;
cout<<" 2. delete the room member and its data "<<endl;
cout<<"enter choice = " ;
cin>>x;
switch(x)
{
case 1:
{
cout<<"what do u want to update ? ";<<endl
cout<<" 1. name "<<endl;
cout<<" 2. date of leaving"<<endl;
cin>>rc;
switch(rc)
{
case 1:
{
cout<<"enter new name = "<<endl;
cin>>name;
}
case 2:
{
cout<<"enter updated date of leaving = ";
cin >>date;
}
}
break;
}
case 2:
{
cout<<"what do you want to be deleted = ";
cout<<" 1. name "<<endl;
cout<<" 2. date of leaving "<<endl;
cin>>hd;
switch(hd)
{
case 1:
{
name==NULL;
break;
}
case 2:
{
dol==NULL;
break;
}
break;
}
}
}
int main()
{
public:
int i,c;
clrscr();
hostel_mangt hm[10];
for(i=0;i<10;i++)
{
hm.oprt_1();
hm.display_1();
cout<<"do u want to continue ? "<<endl<<"if yes enter 1"<<endl;
cin>>c;
if(c!=1)
{
break;
}
}
getch();
return 0:
}
i am using turbo c
i am making a project named hostel management using classes ,array of objects,and switch case because hostel rooms can be empty but if i used normal array,stack,queue it wont work as it does can not have null value in middle
|
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().
Missing closing brace for the hostel_mangt class.
And several other errors such as using comparisons (==) where there should be assignments (=), using public: in the main() function (it shouldn't be there), and so on.
Here's your code with those errors fixed:
#include <iostream>
#include <string>
using namespace std;
class hostel_mangt {
public:
int x, h, id, rc, hd;
string name, dol; // use std::string instead of character arrays, they're much easier to use
// 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_1() {
if (h == 1) {
if (name.empty()) {
cout << "room is empty " << endl;
} else {
cout << "id = " << id << endl;
cout << "name = " << name << endl;
cout << "date of leaving = " << dol << endl;
}
} else {
cout << " 1. Update the room member and its data " << endl;
cout << " 2. delete the room member and its data " << endl;
cout << "enter choice = ";
cin >> x;
switch (x) {
case 1: {
cout << "what do u want to update ? " << endl;
cout << " 1. name " << endl;
cout << " 2. date of leaving" << endl;
cin >> rc;
switch (rc) {
case 1: {
cout << "enter new name = " << endl;
cin >> name;
}
case 2: {
cout << "enter updated date of leaving = ";
cin >> date;
}
}
break;
}
case 2: {
cout << "what do you want to be deleted = ";
cout << " 1. name " << endl;
cout << " 2. date of leaving " << endl;
cin >> hd;
switch (hd) {
case 1: {
name.clear();
// name == NULL;
break;
}
case 2: {
dol.clear();
// dol == NULL;
break;
}
break;
}
}
}
}
}
};
int main() {
int i, c;
clrscr();
hostel_mangt hm[10];
for (i = 0; i < 10; i++) {
// to access an element of an array you use the square brackets []:
hm[i].oprt_1();
hm[i].display_1();
cout << "do u want to continue ? " << endl << "if yes enter 1" << endl;
cin >> c;
if (c != 1) {
break;
}
}
getch();
return 0;
}
There are probably still issues with your code but this is what I managed to fix.
|
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 arbitrary number of indices to erase from a vector? Something like this: v.erase(0, 1, 3);
|
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 elements
v.erase(v.begin(), v.begin() + 2);
|
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";
n /= 10;
} while (n > 0);
}
5
4
3
I want to get same answer with recursive function.
|
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 program it prints the length correctly, but it doesn't print the username at all.
//SERVER
void copyUsername(int fd, char *&username, int &length)
{
printf("Waiting for client login...\n");
if (read(fd, &length, sizeof(int)) == -1)
{
printf("Could not read in the fifo 1\n");
return;
}
printf("Client wrote an username\n");
printf("%d\n", length);
if (read((char)fd, &username, sizeof(char)* length) == -1)
{
printf("Could not read in the fifo 2\n");
return;
}
printf("%s\n", username);
username[strlen(username)] = '\0';
printf("Copied successfully from FIFO %s\n", username);
}
int main()
{
if (mkfifo("fifo1", 0666) == -1)
{
if (errno != EEXIST)
{
printf("Could not create fifo file\n");
return 1;
}
}
int fd = open("fifo1", O_RDWR);
if (fd == -1)
{
printf("Could not open fifo file\n");
return 2;
}
char *username;
int length;
bool connected;
int pfd[2];
if(pipe(pfd) == -1)
{
printf("Could not open the pipe\n");
return 3;
}
int id = fork();
if(id == -1)
{
printf("Could not execute the fork\n");
return 4;
}
if(id == 0)
{
// child process
close(pfd[0]);
copyUsername(fd, username, length);
bool match = matchUsername(username, length);
write(pfd[1], &match, sizeof(match));
close(pfd[1]);
exit(0);
}
else
{
// parent process
close(pfd[1]);
read(pfd[0], &connected, sizeof(connected));
close(pfd[0]);
wait(NULL);
}
|
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 copyUsername, doing username[strlen(username)] = '\0'; is broken. It is a no-op.
It is broken because it assumes the buffer is already 0 terminated.
It is misplaced after the printf
Replace with username[length] = 0;
matchUsername not provided. I had to synthesize this.
client code not provided. It would have helped to show it, so the server can be tested. I've synthesized one in the code below.
Here is the corrected code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#define prte(_fmt...) \
fprintf(stderr,_fmt)
#if DEBUG
#define dbgprt(_fmt...) \
prte(_fmt)
#else
#define dbgprt(_fmt...) \
do { } while (0)
#endif
bool
matchUsername(const char *username, int length)
{
// NOTE: we can ignore the length because copyUsername has 0 terminated the
// string
bool match = strcmp(username,"neo") == 0;
return match;
}
int
copyUsername(int fd, char *username)
{
int length;
dbgprt("Waiting for client login...\n");
if (read(fd, &length, sizeof(int)) == -1) {
prte("Could not read in the fifo 1\n");
return -1;
}
dbgprt("Client wrote an username\n");
dbgprt("%d\n", length);
if (read(fd, username, length) == -1) {
dbgprt("Could not read in the fifo 2\n");
return -1;
}
#if 0
username[strlen(username)] = '\0';
#else
username[length] = '\0';
#endif
dbgprt("%s\n", username);
dbgprt("Copied successfully from FIFO %s\n", username);
return length;
}
int
main(void)
{
if (mkfifo("fifo1", 0666) == -1) {
if (errno != EEXIST) {
printf("Could not create fifo file\n");
return 1;
}
}
int fd = open("fifo1", O_RDWR);
if (fd == -1) {
prte("Could not open fifo file\n");
return 2;
}
char *username;
int length;
bool connected;
int pfd[2];
if (pipe(pfd) == -1) {
prte("Could not open the pipe\n");
return 3;
}
int id = fork();
if (id == -1) {
prte("Could not execute the fork\n");
return 4;
}
if (id == 0) {
// child process
close(pfd[0]);
length = copyUsername(fd, username);
bool match = 0;
if (length > 0)
length = matchUsername(username, length);
write(pfd[1], &match, sizeof(match));
close(pfd[1]);
exit(0);
}
else {
// parent process
close(pfd[1]);
read(pfd[0], &connected, sizeof(connected));
close(pfd[0]);
wait(NULL);
prte("main: connected=%d\n",connected);
}
return 0;
}
In the code above, I've used cpp conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Note: this can be cleaned up by running the file through unifdef -k
Here is the client code I synthesized to test the program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
int
main(int argc,char **argv)
{
--argc;
++argv;
if (argc != 1) {
fprintf(stderr,"no name specified\n");
exit(1);
}
int fd = open("fifo1",O_RDWR);
if (fd < 0) {
perror("open");
exit(1);
}
int length = strlen(*argv);
write(fd,&length,sizeof(length));
write(fd,*argv,length);
close(fd);
return 0;
}
Here is the server output with the command: ./client bork:
main: connected=0
Here is the server output with the command: ./client neo:
main: connected=1
|
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;
cout << d2.c; // clause 3 Error due to c being protected
return 0;
}
Note:
Clause 1 would make c to be protected.
Clause 2 would make c (protected in clause 1) to be public again.
Why clause 3 failed?
|
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 you define class D2 : public D it is equivalent to defining class D2 like this:
class D2
{
protected:
int b=2;
int c=3;
};
|
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 you have any examples or tips on how to do it, pls share you´r thoughts.
Thank you in beforehand!
|
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 object. If either of these conditions is true, then the two reservations overlap.
Here is one possible implementation of the Overlaps function:
bool Reservation::Overlaps(const Reservation& other) const
{
// Check if the start or end date of the other reservation falls between the start and end dates of this reservation.
if ((other.startDate >= this->startDate && other.startDate <= this->endDate) ||
(other.endDate >= this->startDate && other.endDate <= this->endDate))
{
return true;
}
// Check if the start or end date of this reservation falls between the start and end dates of the other reservation.
if ((this->startDate >= other.startDate && this->startDate <= other.endDate) ||
(this->endDate >= other.startDate && this->endDate <= other.endDate))
{
return true;
}
// If none of the above conditions are true, then the reservations do not overlap.
return false;
}
|
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<int> x = new int();
std::unique_ptr<int> x (new int());
Is there a difference in the two syntax for calling the copy constructor?
|
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>
using boost::multiprecision::mpf_float_50;
int main() {
std::vector<mpf_float_50> v(10);
mpf_float_50 step(0.01);
for (size_t i = 0; i < v.size(); ++i) {
v.at(i) = sin(i*step);
}
mpf_float_50 leftPoint(0.0);
boost::math::interpolators::cardinal_cubic_b_spline<mpf_float_50> spline(v.begin(), v.end(), leftPoint, step);
mpf_float_50 x(3.1);
mpf_float_50 tmpVal = spline(x);
std::cout << tmpVal << std::endl;
return 0;
}
When change the type of variables to boost::multiprecision::cpp_bin_float_50 the program is working. Also, boost::multiprecision::mpf_float_50 is working in all other examples I have tried.
The error I get is:
/home/..../main.cpp:19:31: required from here
/usr/include/boost/math/interpolators/detail/cardinal_cubic_b_spline_detail.hpp:50:10: error: conversion from ‘expression<boost::multiprecision::detail::function,boost::multiprecision::detail::abs_funct<boost::multiprecision::backends::gmp_float<50> >,boost::multiprecision::detail::expression<boost::multiprecision::detail::subtract_immediates, boost::multiprecision::number<boost::multiprecision::backends::gmp_float<50> >, long unsigned int, void, void>,[...],[...]>’ to non-scalar type ‘expression<boost::multiprecision::detail::subtract_immediates,boost::multiprecision::number<boost::multiprecision::backends::gmp_float<50> >,long unsigned int,[...],[...]>’ requested
The same error appeared for cpp_dec_float_50, mpfr_float_50 etc. I'm not sure what I'm doing wrong.
|
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 - a);
std::cout << "a:" << a << ", b:" << b << ", c:" << c << std::endl;
}
Prints
a:3, b:2, c:-1
a:3, b:1, c:-1
However, the number<> enables expression templates by default. That means, typeof(F{} - F{}) is not necessarily F, but something like:
namespace mp = boost::multiprecision;
using F = mp::mpf_float_50;
int main() {
F a = 3, b = 2;
mp::detail::expression<mp::detail::subtract_immediates, F, F> //
c = b - a;
Template expressions can greatly optimize some code, e.g. by simplifying evaluation of complicated expressions.
However, some generic code doesn't deal well with the expression templates. Therefore you can turn them off:
namespace mp = boost::multiprecision;
using F = mp::number<mp::gmp_float<50>, mp::et_off>;
Now it all compiles, and probably works as it should.
Live On Coliru
#include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>
#include <iostream>
#include <boost/multiprecision/gmp.hpp>
namespace mp = boost::multiprecision;
using F = mp::number<mp::gmp_float<50>, mp::et_off>;
int main() {
std::vector<F> v(10);
F step(0.01);
for (size_t i = 0; i < v.size(); ++i) {
v.at(i) = sin(i * step);
}
F leftPoint(0.0);
boost::math::interpolators::cardinal_cubic_b_spline<F> spline(v.begin(), v.end(), leftPoint, step);
F x(3.1);
F tmpVal = spline(x);
std::cout << tmpVal << std::endl;
}
Now printing:
0.0449663
|
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 ++) {
dieAfter1Second(); // executes itself after 1 second
}
}
How can i execute dieAfter1Second() for all 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 <iostream> // for std::cout
// Function to make a player die after 1 second
void dieAfter1Second() {
std::cout << "Player died" << std::endl;
}
int main() {
// Set the number of maximum players
const int maxPlayers = 2;
// Wait for 1 second before calling the function for each player
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
while (std::chrono::duration_caststd::chrono::seconds(std::chrono::steady_clock::now() - start).count() < 1) { }
for (int players = 0; players < maxPlayers; players ++) {
dieAfter1Second();
}
return 0;
}
This code will wait for 1 second before calling the dieAfter1Second() function for each player. It will print "Player died" for each player, and they will all die in the same time in the first second.
Note: This code uses the C++11 standard. If you are using an older version of C++, you may need to use a different timer, such as std::clock_t or std::time().
|
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 somehow?
template<class CONFIG>
struct Parent
{
using Type = typename CONFIG::Type;
// Plus a lot more types....
};
template<class CONFIG>
struct Child : public Parent<CONFIG>
{
void x(Type p){} // Compiler error. Cannot see Parent::Type
};
struct Config
{
using Type = int;
// Plus a lot more types....
};
int main()
{
Child<Config> c;
return 0;
}
|
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>
{
using Base = Parent<Config>;
using typename Base::Type;
void x(Type p){} // Compiler error. Cannot see Parent::Type
};
|
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 quite often we'll allocate the memory with GL_DYNAMIC_DRAW.
So far I was thinking of a quad as a pair of triangles, four vertex. How a quad can require 6 vertex?
|
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 texCoord;
void main()
{
float x = -1.0 + float((gl_VertexID & 1) << 2);
float y = -1.0 + float((gl_VertexID & 2) << 1);
texCoord.x = (x+1.0)*0.5;
texCoord.y = (y+1.0)*0.5;
gl_Position = vec4(x, y, 0, 1);
}
And a discussion what pros and cons have these methods.
|
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 -I include
#define ASIO_STANDALONE;
#include <ctime>
#include <iostream>
#include <string>
#include <asio.hpp>
using asio::ip::tcp;
int main()
{
try
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 1326));
for (;;)
{
std::cout << "hi";
tcp::socket socket(io_context);
acceptor.accept(socket);
std::string message = "e";
asio::error_code ignored_error;
asio::write(socket, asio::buffer(message), ignored_error);
break;
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
any help would be much appreciated
|
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 ASIO_STANDALONE
#include <boost/asio.hpp>
#include <ctime>
#include <iostream>
#include <string>
namespace asio = boost::asio;
using asio::ip::tcp;
using boost::system::error_code;
int main() {
try {
asio::io_context io_context;
tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 1326));
for (;;) {
tcp::socket socket(io_context);
acceptor.accept(socket);
std::cout << "hi " << socket.remote_endpoint() << std::endl;
std::string message = "server message works\n";
error_code ignored_error;
asio::write(socket, asio::buffer(message), ignored_error);
break;
}
} catch (std::exception const& e) {
std::cerr << e.what() << std::endl;
}
}
Using netcat to emulate a client:
nc 127.0.0.1 1326 -w 1 <<< "Hello world"
We see:
hi 127.0.0.1:45448
server message works
Or more clearly in separate terminals:
|
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 Value = 20.67;
public:
void print(T val)
{
std::cout << "value :" << val << std::endl;
}
T getValue()
{
return Value;
}
};
int main()
{
int a;
std::cout << "Enter value for a :";
std::cin >> a;
if(a == 10)
{
Demo<int> demoObj1;
demoObj1.print(demoObj1.getValue());
}
else
{
Demo<float> demoObj2;
demoObj2.print(demoObj2.getValue());
}
}
//output:
Enter value for a :10
value :20
and Enter value for a :7
value :20.67
|
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 for both branches. If the compiler can determine at compile time that a branch cannot possibly be taken, a compiler may optimize it away. A simple situation is with the following:
if (4 < 5) {
Demo<int> demoObj1;
demoObj1.print(demoObj1.getValue());
} else {
Demo<float> demoObj2;
demoObj2.print(demoObj2.getValue());
}
In this case, the compiler can see that the second branch will never get executed. The compiler will initially compile both branches, but then it may discard the second branch from the final executable. Whether or not the compiler does this depends on the compiler implementation and compilation flags.
You can force the compiler to reject unused branches with if constexpr. Consider the following example:
if constexpr (4 < 5) {
Demo<int> demoObj1;
demoObj1.print(demoObj1.getValue());
} else {
Demo<float> demoObj2;
demoObj2.print(demoObj2.getValue());
}
All that was changed is that this example uses if constexpr. In this example, the second branch will NOT be fully compiled (it is still checked for correct syntax, but assembly generation is not done). Code for the second branch will not exist in the executable.
|
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";
} while (yn=='y' || yn=='Y');
return 0;
}
First program is showing error like this:
comparison between pointer and integer ('double (*)(int, double)' and 'char')
} while (yn=='y' || yn=='Y');
I think both programs are same but still first program is showing error.
|
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 ill-advised use of using namespace std; moving the entire standard library into the global namespace.
That is what namespaces are for and it is always a bad idea to defeat an entire namespace. Here either use scope resolution std::cout or just declare the symbols you actually use:
using namespace std::cout ;
In this case, with only one instance if a std:: symbol, the using directive has saved you nothing whilst causing a great deal of confusion. Get out if that habit is my advice.
In the second instance you will still get an error, but it will make much more sense, telling you that yn is undefined at the while expression.
All that said, yn() is not a standard library function, but a POSIX extension; it may therefore not be in the std namespace. You may need also to compile with an option that excludes such extensions such as -ansi.
|
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 I can't do it using emp1 or emp2. It would be great if someone can link me to videos where I can learn more on similar topics and better understand classes.
Header File
#ifndef DEPARTMENT_H
#define DEPARTMENT_H
#include <string>
class Employee{
public:
Employee(std::string n, double s);
std::string employee_name;
double salary;
};
class Department{
public:
Department(std::string n, Employee* s, Employee* r);
/*
set the receptionist to r; note that both receptionist and r are pointers
*/
void set_receptionist(Employee* r);
/*
set the secretary to s; note that both secretary and s are pointers
*/
void set_secretary(Employee* s);
/*
calculate the total salary and return it.
neglect the receptionist or secretary if it is nullptr.
count only once if receptionist and secretary point to the same employee (check their address instead of name!)
*/
double get_total_salary() const;
/*
display the department information, including department name, employees, and total salaries.
see details in main function.
neglect the receptionist or secretary if it is nullptr.
*/
void display_department() const;
private:
std::string department_name;
Employee* receptionist;
Employee* secretary;
};
#endif
Implementation File
Employee::Employee(std::string n, double s)
{
employee_name = n;
salary = s;
}
Department::Department(std::string n, Employee* s, Employee* r)
{
department_name = n;
}
void Department::set_receptionist(Employee* r)
{
receptionist = r;
}
void Department::set_secretary(Employee* s)
{
secretary = s;
}
double Department::get_total_salary() const
{
return 0.0;
}
void Department::display_department() const
{
cout << "department name: " << department_name << endl;
cout << "secretary name: " << secretary->employee_name << ", " << "salary: " << secretary->salary << endl;
cout << "receptionist name: " << receptionist->employee_name << ", " << "salary: " << receptionist->salary << endl;
//cout << "total salary: " << << endl;
}
Main File
int main(){
Employee emp1("Alice", 6000);
Employee emp2("Bob", 5500);
Department dep1("IT", &emp1, &emp2);
dep1.display_department();
/*
department name: IT
secretary name: Alice, salary: 6000
receptionist name: Bob, salary: 5500
total salary: 11500
*/
dep1.set_receptionist(&emp1);
dep1.display_department();
/*
department name: IT
secretary name: Alice, salary: 6000
receptionist name: Alice, salary: 6000
total salary: 6000
*/
dep1.set_secretary(nullptr);
dep1.display_department();
/*
department name: IT
receptionist name: Alice, salary: 6000
total salary: 6000
*/
}
The expected output is in the comment of the main file. I am trying to figure out display_department of the Employee class and I know that get_total_salary is incorrect.
Output:
department name: IT
secretary name:
It outputs this and then the program ends.
|
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;
receptionist = r;
}
Then you should test if the pointer equals nullptr before you try an use them to print the secretary or receptionist name.
void Department::display_department() const
{
cout << "department name: " << department_name << endl;
if (secretary == nullptr)
cout << "no secretary:" << endl;
else
cout << "secretary name: " << secretary->employee_name << ", " << "salary: " << secretary->salary << endl;
if (receptionist == nullptr)
cout << "no receptionist:" << endl;
else
cout << "receptionist name: " << receptionist->employee_name << ", " << "salary: " << receptionist->salary << endl;
//cout << "total salary: " << << endl;
}
|
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. I tried to search everything possible but I really couldn't file something useful, plus I am not very familiar to .json language.
Infos :
Code Editor : Visual Studio Code
Task Language : .json
Compiler : g++ Version 2.0.0
Terminal Used For Compiling : Windows PowerShell
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe compila il file attivo",
"command": "C:\\msys64\\mingw64\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": ["$gcc"],
"group": "build",
"detail": "compilatore: C:\\msys64\\mingw64\\bin\\g++.exe"
}
]
}
The normal procedure is to save the file, use the commands I put above, and then run the code from the terminal.
|
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.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
"**/node_modules/**": true
},
"file_watcher": {
"c:\msys64\mingw64\bin\g++.exe": ["${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe"]
}
}
You will need to update the paths in the file_watcher setting to match your local configuration. You may also need to modify the build command and its arguments to match your project's requirements.
|
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 it on the $PATH but didn't work either.
|
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 achieve a result, such that it does not override but simply adds to the string stream. Here is my code below:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
stringstream s1("hello I am string stream");
streambuf *s1_bfr = s1.rdbuf();
ostream my_stream (s1_bfr);
my_stream <<"hey"<<endl;
cout <<s1.rdbuf()<<endl; //gives the result : " hey o I am string stream"( seems to me overriden)
return 0;
}
|
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 stringstream object.
To fix this issue, you can use the ostream::seekp method to move the write position of the ostream object to the end of the stream buffer before writing to it. Here is an example of how you might do this:
stringstream s1("hello I am string stream");
streambuf *s1_bfr = s1.rdbuf();
ostream my_stream (s1_bfr);
my_stream.seekp(0, ios_base::end); // move the write position to the end of the stream
my_stream <<"hey"<<endl;
cout <<s1.rdbuf()<<endl;
After making this change, the output of the program should be "hello I am string streamhey".
Alternatively, you can use the stringstream::str method to retrieve the current contents of the stringstream object as a string, and then append the new string to the end of this string. Here is an example of how you might do this:
stringstream s1("hello I am string stream");
string str = s1.str();
str += "hey\n";
s1.str(str);
cout <<s1.rdbuf()<<endl;
|
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 <iostream>
using namespace std;
int main ()
{
double s=0;
int i=1;
for (int m=1;m<5;m++)
{
i=m*i;
s=s+1/i;
}
cout<<s+1;
return 0;
}
The variable that stores the value of e is s, which is double, so I was expecting that the datatype of i doesn't matter.
|
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 an integer, which is then converted to a double and added to s. This means that some of the fractional parts of the calculation are being lost.
In the first example, where i is a double, the result of the division 1/i is also a double, and the fractional parts of the calculation are preserved. This is why the output is different in the two cases.
One way to fix this would be to use the 1.0 instead of 1 in the division, like this:
#include <iostream>
using namespace std;
int main ()
{
double s=0;
int i=1;
for (int m=1;m<5;m++)
{
i=m*i;
s=s+1.0/i;
}
cout<<s+1;
return 0;
}
This way, the 1.0 will be treated as a double, and the result of the division will also be a double, so the fractional parts of the calculation will be preserved.
|
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<Derived>(dynamic_cast<Derived*>(ptr.release()));
}
|
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 will fail
auto d2p = cast_to<Base, Derived2>(std::move(bp));
std::cout << bp.get() << '\n'; // 0
std::cout << d2p.get() << '\n'; // also 0; object was leaked
}
Demo
From this snippet you can also see another small issue: because of the order of the template parameters you have to supply them both. You can't let the compiler deduce Base because it comes before Derived.
With both of those issues in mind, the following would be a better implementation:
template<typename Derived, typename Base> // swap the order of template parameters
requires std::is_convertible_v<Derived&, Base&> &&
std::is_polymorphic_v<Base>
inline std::unique_ptr<Derived> cast_to(std::unique_ptr<Base>&& ptr)
{
Derived* d = dynamic_cast<Derived*>(ptr.get());
if (d) {
ptr.release();
return std::unique_ptr<Derived>(d);
}
return nullptr; // object is still owned by ptr
}
This fixes both of the above issues:
int main()
{
std::unique_ptr<Base> bp = std::make_unique<Derived1>();
// No need to explicitly specify Base; the compiler can deduce that itself
auto d2p = cast_to<Derived2>(std::move(bp));
std::cout << bp.get() << '\n'; // not 0; no leak
std::cout << d2p.get() << '\n'; // 0
}
Demo
|
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"}};
for (const auto& [key, val] : rmap) {
std::cerr << typeid(bool).hash_code() << "\n";
std::cerr << typeid(decltype(key)).hash_code() << "\n";
std::cerr << smap<bool>.size() << "\n";
std::cerr << smap<decltype(key)>.size() << "\n";
assert((std::is_same_v<bool, decltype(key)>));
}
return 0;
}
Godbolt
It gives the output:
10838281452030117757
10838281452030117757
1
0
example.cpp:22: int main(): Assertion `(std::is_same_v<bool, decltype(key)>)' failed.
Why is it that I can't access the variable template using decltype when it's referring to the same type (bool)?
For the record I also tried to not use structured binding and using decltype on first in the pair with the same result.
However if I create an actual bool variable, like so ...
bool b;
std::cerr << settings_map<decltype(b)>.size() << "\n";
... it's working.
|
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 while typeid treats the two types as equivalent, template expansion (and is_same_v) does not, and you get two different maps: one for bool and one for const bool. Note that the assertion
assert((std::is_same_v<const bool, decltype(key)>));
succeeeds if put in place of the one in your code. To remove cv-qualifiers, use remove_cv_t.
std::cerr << settings_map<std::remove_cv_t<decltype(key)>>.size() << "\n";
In your last snippet
bool b;
std::cerr << settings_map<decltype(b)>.size() << "\n";
The b is not constant, so decltype(b) is actually bool, not const bool.
|
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::cout << ("70" < "60") << '\n';
return 0;
}
both print
1
0
The same holds true for std::less<>(). However, std::less<std::string>() provides the correct lexicographical comparison. What is the reason for this behaviour?
Are the comparisons shown above comparing the addresses of char arrays?
|
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 their addresses.
So any possible outcome for your tests is allowed. 0/0 as well as 0/1, 1/0 and 1/1.
You can avoid all the C-style array behavior of string literals by always using std::string or std::string_view literals instead:
#include <iostream>
using namespace std::string_literals;
int main () {
std::cout << ("70"s < "60"s) << '\n';
std::cout << ("60"s < "70"s) << '\n';
return 0;
}
This uses the user-defined string literal operator""s from the standard library to immediately form std::strings from the string literals. sv can be used for std::string_views instead. (string_view will incur less performance cost, in particular no dynamic allocation.)
|
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 know if you have the answer.
|
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 struct
tm *time = std::localtime(&now);
// Print the current time and date
std::cout << "The current time and date is " << time->tm_year + 1900
<< "-" << time->tm_mon + 1 << "-" << time->tm_mday
<< " " << time->tm_hour << ":" << time->tm_min
<< ":" << time->tm_sec << std::endl;
return 0;
}
In this example, the std::time() function is called with a NULL argument to get the current time in seconds. The value returned by the std::time() function is then printed to the console using the std::cout object.
You can use the std::localtime() function to convert the Unix timestamp to a more human-readable format. This function returns a tm struct that contains the local time broken down into its component parts (year, month, day, hour, minute, etc.).
|
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;
};
Goals:
A directed graph G (what is the difference between a bidirectional and directed other than in_edges please?)
G can hold the vertex type Vertex.
get the vertex by id from G and change the value m_d in the Vertex struct when I want.
add, remove verticies and edges between verticies and also supports costs i.e. cost(edge).
Could you please write me an example on how to do this with BGL please? I beleive I need MutableBidirectionalGraph?
|
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 bidirectional and directed other than
in_edges please?)
There is no other difference, except of course the complexity guarantees
for enumerating incoming edges, and a linear overhead upon insertion of edges
G can hold the vertex type Vertex.
See 0.
get the vertex by id from G
auto find_by_id = [&g](size_t id) -> Vertex& {
auto vv = boost::make_iterator_range(vertices(g));
auto vd = find_if(vv, [&, id](auto vd) { return g[vd].m_id == id; });
return g[*vd];
};
and change the value m_d in the Vertex struct when I want.
if (i_want()) {
g[vd].m_id += 1;
}
Or,
auto idmap = boost::get(&Vertex::m_id, g);
if (i_want()) {
idmap[vd] += 1;
}
or even
put(idmap, vd, 42);
or even more unmarked:
get(boost::vertex_bundle, g, vd).m_id = 999;
add, remove vertices
remove_vertex(vd, g);
and edges between vertices
clear_vertex(vd, g);
and also supports costs i.e. cost(edge).
Wow that really has nothing to do with any of the above. But it's really the same as with vertex ids:
if (i_want()) {
g[ed].cost = new_cost;
}
Or,
auto cost = boost::get(&Edge::cost, g);
if (i_want()) {
cost[ed] = new_cost;
}
or even
put(cost, ed, new_cost);
or even more unmarked:
get(boost::edge_bundle, g, ed).cost = new_cost;
Live Demo
Live On Coliru
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/range/algorithm.hpp>
#include <iostream>
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>;
using boost::make_iterator_range;
int main(){
Graph g;
auto v0 = add_vertex({0.1, 100}, g);
auto v1 = add_vertex({0.2, 200}, g);
auto v2 = add_vertex({0.3, 300}, g);
auto v3 = add_vertex({0.4, 400}, g);
auto v4 = add_vertex({0.5, 500}, g);
auto v5 = add_vertex({0.6, 600}, g);
add_edge(v0, v2, Edge{1.5}, g);
add_edge(v1, v3, Edge{2.5}, g);
add_edge(v4, v1, Edge{3.5}, g);
add_edge(v2, v5, Edge{4.5}, g);
auto idmap = boost::get(&Vertex::m_id, g);
auto cost = boost::get(&Edge::cost, g);
auto find_by_id = [&g](size_t id) -> Vertex& {
auto vv = boost::make_iterator_range(vertices(g));
auto vd = find_if(vv, [&, id](auto vd) { return g[vd].m_id == id; });
return g[*vd];
};
print_graph(g, idmap, std::cout << "original: ");
auto i_want = [](auto vd) {
return (vd % 2); // when I want
};
for (auto vd : make_iterator_range(vertices(g))) {
if (i_want(vd))
g[vd].m_id += 1;
if (i_want(vd))
idmap[vd] += 1;
//put(idmap, vd, 42);
//get(boost::vertex_bundle, g, vd).m_id = 999;
}
print_graph(g, idmap, std::cout << "altered: ");
clear_vertex(v3, g);
remove_vertex(v3, g); // undefined behaviour unless edges cleared
print_graph(g, idmap, std::cout << "removed: ");
for (auto ed : make_iterator_range(edges(g))) {
std::cout << ed << " cost " << cost[ed] << "\n";
}
for (auto ed : make_iterator_range(edges(g))) {
cost[ed] *= 111;
}
for (auto ed : make_iterator_range(edges(g))) {
std::cout << ed << " cost " << cost[ed] << "\n";
}
};
Prints
original: 100 --> 300
200 --> 400
300 --> 600
400 -->
500 --> 200
600 -->
altered: 100 --> 300
202 --> 402
300 --> 602
402 -->
500 --> 202
602 -->
removed: 100 --> 300
202 -->
300 --> 602
500 --> 202
602 -->
(0,2) cost 1.5
(3,1) cost 3.5
(2,4) cost 4.5
(0,2) cost 166.5
(3,1) cost 388.5
(2,4) cost 499.5
|
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 the value y refers to? You cannot do it simply, and must resort to accessors, or any non-const function (e.g. operator=):
class U
{
int& _y;
public:
int x;
void setY(int y) { _y = y; } // cannot be called on const U
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.