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 |
|---|---|---|---|---|
72,003,506 | 72,003,837 | How constructor and destructor called during template object in c++ | Can you please explain how constructor and destructor is called,Because when i see the output for tempravary object 4 destructor called more times
output
item Args constructor called 1
1 100
item Args constructor called 2
2 Proffecessor
item Args constructor called 4
item Args constructor called 3
item desconstructor called 4
3 4 Professor
item desconstructor called 4
item desconstructor called 4
item desconstructor called 3
item desconstructor called 4
item desconstructor called 2
item desconstructor called 1
#include<iostream>
#include<string>
using namespace std;
template <typename template_type>
class item
{
string name;
template_type value;
public:
item(string name, template_type value)
:name{name}, value{value}
{
cout<<"item Args constructor called "<<name<<endl;
}
~item()
{
cout<<"item desconstructor called "<<name<<endl;
}
string get_name()const
{
return name;
}
template_type get_value()const
{
return value;
}
};
int main()
{
item<int> item1{"1", 100 };
cout<<item1.get_name()<<" "<<item1.get_value()<<endl;
item<string> item2{"2", "Proffecessor" };
cout<<item2.get_name()<<" "<<item2.get_value()<<endl;
item<item<string>> item3{"3", {"4","Professor"}};
cout<<item3.get_name()<<" "
<<item3.get_value().get_name()<<" "
<<item3.get_value().get_value()<<endl;
}
| You miss the copy constructor. That's why you see more destructor call than constructor. You can also see it with this code.
#include<iostream>
#include<string>
using namespace std;
template <typename template_type>
class item
{
string name;
template_type value;
public:
item(string name, template_type value):name{name}, value{value}
{
cout<<"item Args constructor called "<<name<<endl;
}
/* you miss the copy constructor
item(const item&)
{
cout<<"item copy" <<endl;
}
*/
~item()
{
cout<<"item desconstructor called "<<name<<endl;
}
};
void foo(item<int> i){}
int main()
{
item<int> item1{"1", 100 };
foo(item1);
}
output
item Args constructor called 1
item desconstructor called 1
item desconstructor called 1
https://godbolt.org/z/xhWh9hGr6
|
72,004,031 | 72,004,370 | How do I get Arduino to return to 0 degrees after turning to 90 degrees | I am working on a project at the moment that deploy a model rockets parachute. I am not very skilled at coding so I thought I would ask here. The code is designed to press a button on the ground with a timer and then the parachute is deployed by the servo moving to 90 degrees. I would like the servo to return to 0 degrees after ward without having to press the button again. Would this code work?
#include <Servo.h>
// constants won't change
const int BUTTON_PIN = 7;
const int SERVO_PIN = 9;
Servo servo;
int angle = 0;
int lastButtonState;
int currentButtonState;
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
servo.attach(SERVO_PIN);
servo.write(angle);
currentButtonState = digitalRead(BUTTON_PIN);
}
void loop() {
lastButtonState = currentButtonState;
currentButtonState = digitalRead(BUTTON_PIN);
if(lastButtonState == HIGH && currentButtonState == LOW) {
Serial.println("The button is pressed");
delay(10000);
if(angle == 0)
angle = 90;
else
if(angle == 90)
angle = 0;
delay(5000);
servo.write(0);
}
}
| Currently you are waiting for 10 seconds (10 000ms) after the button has been pressed. After the button has been pressed nothing is done except for the Serial.println(...). You then check the if/else statement once. For your code to work you would want something like
if (buttonPressed == true) {
// Wait for 10 seconds
delay(10000);
// Turn servo to 90 degrees
servo.write(90);
// Wait for 5 seconds
delay(5000);
// Turn servo to 0 degrees
servo.write(0);
}
To detect that your button is pressed you will probably want to add a debounce (check https://www.arduino.cc/en/Tutorial/BuiltInExamples/Debounce), but the debounce should not change the logic when the button is detected to be pressed. The debounce only prevents triggering multiple button pressed detections.
|
72,004,319 | 72,004,499 | Difference between std::vector::empty and std::empty | To check if a vector v is empty, I can use std::empty(v) or v.empty(). I looked at the signatures on cppreference, but am lacking the knowledge to make sense of them. How do they relate to each other? Does one implementation call the other?
I know that one comes from the containers library and the other from the iterators library, but that is about it.
|
Difference between std::vector::empty and std::empty
The difference between Container::empty member function and std::empty free function (template) is the same as difference between Container::size,std::size, Container::data,std::data, Container::begin,std::begin and Container::end,std::end.
In all of these cases for any standard container, the free function (such as std::empty) simply calls the corresponding member function. The purpose for the existence of the free function is to provide a uniform interface between containers (and also std::initializer_list) and arrays. Arrays cannot have member functions like the class templates can have, so they have specialised overload for these free functions.
If you are writing code with a templated container type, then you should be using the free function in order to be able to support array as the templated type. If the type isn't templated, then there is no difference between the choice of using member function or the free function other than the convenience of potential refactoring into a template (or just plain array).
|
72,004,573 | 72,004,656 | Initialize vector without copying and using move semantics | Is there a way to avoid copying when initializing a vector?
The code below will produce the following output.
#include <iostream>
#include <vector>
using namespace std;
struct Ticker {
std::string m_ticker;
Ticker() {
std::cout << "Default constructor" << std::endl;
}
Ticker(const std::string& ticker)
: m_ticker(ticker)
{
std::cout << "Parametrized constructor" << std::endl;
}
Ticker(Ticker&& other)
{
std::cout << "Move constructor" << std::endl;
m_ticker = other.m_ticker;
other.m_ticker = "";
}
Ticker(const Ticker& x)
{
std::cout << "Copy constructor" << std::endl;
m_ticker = x.m_ticker;
}
~Ticker()
{
std::cout << "Destructor" << std::endl;
}
friend std::ostream& operator << (std::ostream& os, const Ticker& dr);
};
std::ostream& operator << (std::ostream& os, const Ticker& dr)
{
os << "|" << dr.m_ticker << "|";
return os;
}
int main() {
std::vector<Ticker> table = std::move(std::vector<Ticker>{std::move(Ticker("MSFT")), std::move(Ticker("TSL"))});
for (const auto& row: table)
{
std::cout << row << std::endl;
}
return 0;
}
This produces the following output:
Parametrized constructor
Move constructor
Parametrized constructor
Move constructor
Copy constructor
Copy constructor
Destructor
Destructor
Destructor
Destructor
|MSFT|
|TSL|
Destructor
Destructor
Is there a way to avoid the copy constructor and initialize in-place or just move without copying?
| If you use
std::vector<Ticker> table = std::vector<Ticker>{Ticker("MSFT"), Ticker("TSL")};
You will get
Parametrized constructor
Parametrized constructor
Copy constructor
Copy constructor
Destructor
Destructor
|MSFT|
|TSL|
Destructor
Destructor
Which has 4 constructor calls instead of the 6 you currently have. 2 of those calls are for Ticker("MSFT") and Ticker("TSL") and then the additional two copies are because initializer lists store the elements in them as const, so they have to be copied into the vector as you can't move from a const object.
To get the bare minimum of 2 constructor calls you'll need to use the emplace_back member function like
std::vector<Ticker> table; // create empty vector
table.reserve(2); // allocate space for 2 Tickers but create nothing
table.emplace_back("MSFT"); // directly construct from "MSFT" in the reserved space
table.emplace_back("TSL"); // directly construct from "TSL" in the reserved space
which has the output of
Parametrized constructor
Parametrized constructor
|MSFT|
|TSL|
Destructor
Destructor
If you want a syntax like std::vector<Ticker> table = std::vector<Ticker>{Ticker("MSFT"), Ticker("TSL")};, but without the extra overhead, you could wrap the emplace_back solution in a factory function like
template <typename T, typename... Args>
auto make_vector(Args&&... args)
{
std::vector<T> data;
data.reserve(sizeof...(Args));
(data.emplace_back(std::forward<Args>(args)), ...);
return data;
}
and then you would use it like
auto table = make_vector<Ticker>("MSFT", "TSL");
|
72,005,386 | 72,005,756 | Possible memory leak from a handled exception? (With exception handling that calls exit().) | I'm working on a C++ application (an OpenSSL assignment for university), and I'm running it through valgrind, as one does. I've noticed some rather strange output when the program fails due to invalid input:
==1739== HEAP SUMMARY:
==1739== in use at exit: 588 bytes in 6 blocks
==1739== total heap usage: 52 allocs, 46 frees, 99,206 bytes allocated
==1739==
==1739== 44 bytes in 1 blocks are possibly lost in loss record 3 of 6
==1739== at 0x483BE63: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==1739== by 0x4C20378: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)
==1739== by 0x4C03187: std::logic_error::logic_error(char const*) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)
==1739== by 0x4C0325C: std::invalid_argument::invalid_argument(char const*) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)
==1739== by 0x10FB6D: lab2::cryptoEngine::CBCCryptoEngine::encrypt() (CBCCryptoEngine.cpp:39)
==1739== by 0x10E355: main (main.cpp:135)
==1739==
==1739== 144 bytes in 1 blocks are possibly lost in loss record 4 of 6
==1739== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==1739== by 0x4BDB1F3: __cxa_allocate_exception (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)
==1739== by 0x10FB5B: lab2::cryptoEngine::CBCCryptoEngine::encrypt() (CBCCryptoEngine.cpp:39)
==1739== by 0x10E355: main (main.cpp:135)
==1739==
==1739== LEAK SUMMARY:
==1739== definitely lost: 0 bytes in 0 blocks
==1739== indirectly lost: 0 bytes in 0 blocks
==1739== possibly lost: 188 bytes in 2 blocks
==1739== still reachable: 400 bytes in 4 blocks
==1739== of which reachable via heuristic:
==1739== stdstring : 44 bytes in 1 blocks
==1739== suppressed: 0 bytes in 0 blocks
==1739== Reachable blocks (those to which a pointer was found) are not shown.
==1739== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==1739==
==1739== For lists of detected and suppressed errors, rerun with: -s
The code causing it is just a regular exception that is thrown when an input file is invalid. The exception is caught properly like this:
try {
engine.encrypt(bad_argument); // Placeholder. The exception type stands, though...
}
catch (const std::invalid_argument &e) {
std::cerr << "Exception while encrypting file: " << e.what() << std::endl;
delete (engine);
exit(EXIT_FAILURE);
}
I'm not 100% sure what it means, and if it is even a problem, since the memory will be reclaimed by the OS anyway. But I've never seen this kind of thing before, and wanted to check.
So, my question is, what is it caused by? Should I fix it? If so, how?
| std::logic_error's constructor allocated memory for the "explanatory string". This is what() returns to you, in the exception handler (std::invalid_argument inherits from std::logic_error).
Observe that the backtrace shows the constructor overload that takes a const char * for a parameter. It would've been acceptable if that literal const char * got stashed away, and handed back to you from what(). However there are various immaterial reasons why the constructor is coded to make a copy of the "explanatory string" so that its contents are wholly owned by the constructed std::logic_error.
Your exception handler quietly called exit() and the process terminated. At which point valgrind notified you that the aforementioned allocated memory wasn't destroyed. This is true, that memory wasn't deallocated.
Had your exception handler's scope ended naturally (without calling exit()), std::logic_error's destructor would've deleted the allocated memory, and everyone would've lived happily ever after.
TLDR: this is only a technical memory leak. It is technically true only because the rug was pulled from under the process, by calling exit.
Note that valgrind said "possibly" instead of "definitely". There's no doubt that you have a memory leak when valgrind "definitely" claims one. If it's just "possibly", then there may or may not be a real memory leak.
|
72,006,166 | 72,007,960 | Is it possible to efficiently get a subset of rows from a large fixed-width CSV file? | I have an extremely large fixed-width CSV file (1.3 million rows and 80K columns). It's about 230 GB in size. I need to be able to fetch a subset of those rows. I have a vector of row indices that I need. However, I need to now figure out how to traverse such a massive file to get them.
The way I understand it, C++ will go through the file line by line, until it hits the newline (or a given delimiter), at which point, it'll clear the buffer, and then move onto the next line. I have also heard of a seek() function that can go to a given position in a stream. So is it possible to use this function somehow to get the pointer to the correct line number quickly?
I figured that since the program doesn't have to basically run billions of if statements to check for newlines, it might improve the speed if I simply tell the program where to go in the fixed-width file. But I have no idea how to do that.
Let's say that my file has a width of n characters and my line numbers are {l_1, l_2, l_3, ... l_m} (where l_1 < l_2 < l_3, ... < l_m). In that case, I can simply tell the file pointer to go to (l_1 - 1) * n, right? But then for the next line, do I calculate the next jump from the end of the l_1 line or from the beginning of the next line? And should I include the newlines when calculating the jumps?
Will this even help improve speed, or am I just misunderstanding something here?
Thanks for taking the time to help
EDIT: The file will look like this:
id0000001,AB,AB,AA,--,BB
id0000002,AA,--,AB,--,BB
id0000003,AA,AA,--,--,BB
id0000004,AB,AB,AA,AB,BB
| As I proposed in the comment, you can compress your data field to two bits:
-- 00
AA 01
AB 10
BB 11
That cuts your file size 12 times, so it'll be ~20GB. Considering that your processing is likely IO-bound, you may speed up processing by the same 12 times.
The resulting file will have a record length of 20,000 bytes, so it will be easy to calculate an offset to any given record. No new line symbols to consider :)
Here is how I build that binary file:
#include <fstream>
#include <iostream>
#include <string>
#include <chrono>
int main()
{
auto t1 = std::chrono::high_resolution_clock::now();
std::ifstream src("data.txt", std::ios::binary);
std::ofstream bin("data.bin", std::ios::binary);
size_t length = 80'000 * 3 + 9 + 2; // the `2` is a length of CR/LF on my Windows; use `1` for other systems
std::string str(length, '\0');
while (src.read(&str[0], length))
{
size_t pos = str.find(',') + 1;
for (int group = 0; group < 2500; ++group) {
uint64_t compressed(0), field(0);
for (int i = 0; i < 32; ++i, pos += 3) {
if (str[pos] == '-')
field = 0;
else if (str[pos] == 'B')
field = 3;
else if (str[pos + 1] == 'B')
field = 2;
else
field = 1;
compressed <<= 2;
compressed |= field;
}
bin.write(reinterpret_cast<char*>(&compressed), sizeof compressed);
}
}
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() << std::endl;
// clear `bad` bit set by trying to read past EOF
src.clear();
// rewind to the first record
src.seekg(0);
src.read(&str[0], length);
// read next (second) record
src.read(&str[0], length);
// read forty second record from start (skip 41)
src.seekg(41 * length, std::ios_base::beg);
src.read(&str[0], length);
// read next (forty third) record
src.read(&str[0], length);
// read fifties record (skip 6 from current position)
src.seekg(6 * length, std::ios_base::cur);
src.read(&str[0], length);
return 0;
}
This can encode about 1,600 records in a second, so the whole file will take ~15 minutes. How long does it take you now to process it?
UPDATE:
Added example of how to read individual records from src.
I only managed to make seekg() work in binary mode.
|
72,006,351 | 72,006,403 | C++ Using Time as variable to store event length to reproduce later | Long story short:
I am trying to measure the time difference between the start & end of an event (a device executing a command), because I want to reproduce that later on as a return Home command.
But, it seems that for the same event, the time is way different, it varies by a factor of x2.
Here is my testing code:
#include <stdio.h>
#include <time.h>
#include <iostream>
using namespace std;
int main ()
{
clock_t t;
t = clock();
for(int i =0; i < 50; i++) { cout << i << " ";}
t = clock() - t;
printf ("\nIt took me %d clicks (%f seconds).\n", t, ((double) t) / CLOCKS_PER_SEC);
return 0;
}
Does anyone know anything better to get better results?
Context:
Sending commands to a device via BlueTooth, like rotating both motors at X speed while the VK_UP key is pressed, and stopping motors when VK_UP is released. The idea is to map all these commands using execution time between keypressed-keyreleased and later on to build a Return Home function.
| Well, first, consider measure time using C++ facilities like in this question:
Measuring execution time of a function in C++
Then, the execution time of a piece of code may be impacted by many circumstances, so you should treat it like a random variable of sorts, and measure it multiple times, or measure the sum of times and divide by the number of repetitions.
Finally, your computer is not spending all of its time just executing your program; so - you may want to use something like time program, or a profiler application, to figure out how much processor time your program actually got.
|
72,006,709 | 72,006,884 | How do I get the C++ standard flag as a string in CMake? | I need to get the compiler flags that will be used to compile a target programmatically in CMake. I need these flags as a string because I need to pass them to an executable in a custom command that needs to know how the parent target was compiled because it propagates those flags. I know enabling compile commands generates a JSON that shows the compile command but I need that output in CMake itself.
project(foo LANGUAGES CXX)
cmake_minimum_required(VERSION 3.22)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_executable(bar bar.cpp)
# define COMPILE_FLAGS somehow such that it equals -std=c++17
add_custom_target(external
COMMAND external_exe --flags ${COMPILE_FLAGS}
)
I've looked at these previous questions:
Using something like this or this does print compile flags like "-Werror" but the standard flag is not printed
Setting the standard with set_property and then getting it returns "17". Similarly, I can get the CMAKE_CXX_STANDARD to also return "17"*
This is the exact problem I have but the answer doesn't help in CMake
These questions are also related but unhelpful: one, two, and three
Am I missing something or is there no way to get this information?
*Can I assume that getting the standard number (e.g. 17) and appending that to "-std=c++" will be portably valid? It works with g++ at least but I'm not sure about other compilers/platforms.
| If you just need the compiler flag for choosing the C++ standard, try this:
set(COMPILE_FLAG ${CMAKE_CXX${CMAKE_CXX_STANDARD}_STANDARD_COMPILE_OPTION})
Alternatively, replace "STANDARD" in the code above with "EXTENSION" if you want to allow compiler-specific extensions.
I grepped through the CMake source code, and I found that variables like CMAKE_CXX17_STANDARD_COMPILE_OPTION are defined in files that tell CMake how to use different compilers.
|
72,006,755 | 72,006,955 | Filling in a vector with random numbers | I'm trying to print random numbers using srand. This is my code.
I want each subsequent number larger than the previous number in the list.
This is my code.
#include <iostream>
#include <ctime>
#include <cmath>
#include <random>
#include <vector>
#include <algorithm>
#include <climits> // for INT_MAX;
int main(){
srand((int)time(0));
std::vector<int> myVec;
int number = 5;
for(size_t index = 0; index <100; index++){
int result = (rand() % number) +1;
if((result % 5) == 0 or (result % 5 == 3 && index == 50)){
number += 2;
myVec.push_back(number);
}
}
for(int vec : myVec){
std::cout << vec << " ";
}
return 0;
}
The output I'm looking for is
0 2 4 6 9 12 so on
Can someone please guide me on how can I achieve it?
| You should be able to write this a lot simpler. Also, the reason your code seems to be not getting any random values is because your pushing back your bound with myVec.push_back(number). You should instead be doing myVec.push_back(result).
As for your actual question, it doesn't seem like your code is written as to what you're trying to achieve. If you want to get values 0-4 greater than the subsequent value, it would be better to write it something like this:
#include <iostream>
#include <ctime>
#include <random>
#include <vector>
int main(){
srand(time(0));
std::vector<int> nums;
int lower = 0;
for(int i=0; i<100; i++) {
// generate random number from lower bound to upper bound
// starting lower bound is 0
nums.push_back((rand() % 5) + lower);
lower = nums[nums.size()-1];
}
for(int num : nums){
std::cout << num << " ";
}
std::cout << "\n";
return 0;
}
So, generally, if a random function is returning any value x where 0 <= x < 1 (which I believe C/C++ rand() does), then to get a value within a given range you want to have it in this format:
(rand() % (upper_bound - lower_bound + 1)) + lower_bound
However, you said that you want all values to be 0-4 greater than the lower bound. This means we essentially want to start from our lower bound, and add 0-4 to it. So really, we just need to generate a random number from 0-4. The code above does rand() % 5 because rand() % N will return any number x where 0 <= x < N. So, we want to do rand() % 5 which will get any number from 0 to 4.
Also, this is just semantics, but in my personal experience it's always good to try and maintain some level of inference with your variable naming. In your for-each loop you wrote for(int vec : myVec), but to the glancing eye this may appear that myVec is actually a vector of vectors, and every element of myVec is a vector itself. Although the type int is clearly declared, it's still easy to get confused as to why the developer named it "vec" if its type is not a vector. Once again, some of this comes down to preference and if this is for a personal project, assignment, or actual production code. But I'd start making a good habit of making sure things are named intentionally and purposefully.
|
72,007,489 | 72,007,522 | C++; Pass std::array as a Function Parameter | I know this is a common question, but how do I pass a std::array as a function parameter? I've looked at answers for other questions on here asking the same thing, and the best "solution" I found was to use a template to set size_t to a keyword like SIZE. I tried this, but it still gives me two compile time errors:
Error C2065 'SIZE': undeclared identifier
Error C2975 '_Size': invalid template argument for 'std::array', expected compile-time constant expression
Both errors on the line where I have my void function definition.
As far as I know, I did this exactly how the solution was typed out. I know I could instead pass through a std::vector, but I'm stubborn and want to learn this.
Here is my relevant code:
#include <iostream>
#include <array>
using namespace std;
template<size_t SIZE>
void QuickSort(array<unsigned, SIZE>& arrayName);
int main()
{
// main function.
}
void QuickSort(array<unsigned, SIZE>& arrayName)
{
// whatever the function does.
}
I'd appreciate any help figuring out what it is that I'm doing wrong.
EDIT: I forgot to take out the second function parameter. I did that, but still the same issues.
| Your function definition still needs template parameters since the compiler has no way of knowing what SIZE is
template<size_t SIZE>
// ^^^^^^^^^^^^^^^^^^
void QuickSort(array<unsigned, SIZE>& arrayName)
{
/// whatever the function does.
}
|
72,007,867 | 72,008,448 | Can a constructor affect other fields of an enclosing object, or is this a static analysis false positive? | Consider this C++ code:
struct SomeStruct {
SomeStruct() noexcept;
};
//SomeStruct::SomeStruct() noexcept {}
class SomeClass {
const bool b;
const SomeStruct s;
public:
SomeClass() : b(true) {}
operator bool() const { return b; }
};
void f() {
int *p = new int;
if (SomeClass())
delete p;
}
When I run clang --analyze -Xanalyzer -analyzer-output=text on it, I get this:
q72007867.cpp:20:1: warning: Potential leak of memory pointed to by 'p' [cplusplus.NewDeleteLeaks]
}
^
q72007867.cpp:17:12: note: Memory is allocated
int *p = new int;
^~~~~~~
q72007867.cpp:18:7: note: Assuming the condition is false
if (SomeClass())
^~~~~~~~~~~
q72007867.cpp:18:3: note: Taking false branch
if (SomeClass())
^
q72007867.cpp:20:1: note: Potential leak of memory pointed to by 'p'
}
^
1 warning generated.
Uncommenting the definition of SomeStruct's constructor makes the warning go away, though. Swapping the order of const bool b; and const SomeStruct s; also makes it go away. In the original program, is there actually some other definition of SomeStruct's constructor that would lead to the false branch being taken there, or is this a false positive in Clang's static analyzer?
| There is no standard compliant way for a const member to be changed after initialization; any mechanism is going to be UB.
Like
struct foo{
const bool b=true;
foo(){ b=false; }
};
is illegal, as is code that const_casts b to edit it like:
struct foo{
const bool b=true;
foo(){ const_cast<bool&>(b)=false; }
};
(this second version compiles, but produces UB).
Such UB is sadly not that rare. For example, I could implement the constructor of SomeStruct to fiddle with memory before the this pointer address. It would be doubly illegal (modifying a const value after construction, and violating reachability rules), but depending on optimization settings it could work.
On the other hand, the compiler is free to notice that the only constructor assigns true to b and then convert operator bool to just return true.
But instead, the static code analyzer gives up on provong the state of b once a call to a function body outside of the visible source code occurs. This is a pretty reasonable thing to give up on. Here, the function even gets a pointer into the same temporary object; doing a full proof that said pointer cannot change some state regardless of what code is run is possible, but failing to do that seems also reasonable.
Style wise, the code is also a bit of a mess. A provably true branch either should not exist, or the failure branch should semantically make sense. Neither occurs here; anyone reading this code cannot determine correctness from code structure; the code structure looks misleading.
|
72,008,655 | 72,009,330 | How to throw an exception if two different derived class objects from the same base class interact with each other? | I have an abstract base class(X) with A & B derived classes.
I have a class method in X that is inherited by both classes A & B.
I want the method to be able to throw an exception if two different derived class objects interact with each other.
Here is a contrived example:
class Food{
public:
int count;
void combine(Food* a) {
this->count += a->count;
}
};
class Orange : Food {
public:
Orange(int x) {
count = x;
}
};
class Apple : Food{
public:
Apple(int x) {
count = x;
}
};
int main() {
Food* basket_apples = new Apple(5);
Food* basket_oranges = new Orange(4);
Food* crate_oranges = new Orange(10);
crate_oranges.combine(basket_oranges);//should work fine
crate_oranges.combine(basket_apples); //should produce error
}
A solution I considered is to override the combine method in both derived classes but that violates DRY(Don't repeat yourself).
I want to know if there are any other options to solve this issue.
| You can check that in the combine function :
void combine(Food const& a) // You should pass your argument by const ref
{
assert(typeid(*this) == typeid(a)); // This checks ONLY IN DEBUG !
this->count += a.count;
}
If you want to manage the error, use exception or return value :
void combine(Food const& a)
{
if(typeid(*this) != typeid(a))
throw std::runtime_error("Invalid combined types");
this->count += a.count;
}
int combine(Food const& a)
{
if(typeid(*this) != typeid(a))
return 1;
this->count += a.count;
return 0;
}
Maybe you should transfert the counter ?
void combine(Food& a) // Passing by non-const reference
{
assert(typeid(*this) == typeid(a));
this->count += a.count;
a.count = 0;
}
Note: As said by user17732522, your member function combine should be virtual and the class should better manage the inheritence. I suggest this :
class Food
{
protected:
std::size_t count; // You want this value >= 0
public:
Food(std::size_t count_) : count(count_) {}
Food(Food const& f) : count(f.count) {}
virtual ~Food() {}
virtual std::string name() const = 0;
virtual void combine(Food const& a)
{
assert(typeid(a) == typeid(*this));
this->count += a.count;
}
};
class Orange : public Food
{
public:
Orange(std::size_t x) : Food(x) {}
Orange(Orange const& o) : Food(o) {}
virtual ~Orange() {}
virtual std::string name() const { return "orange"; }
};
class Apple : public Food
{
public:
Apple(std::size_t x) : Food(x) {}
Apple(Apple const& a) : Food(a) {}
virtual ~Apple() {}
virtual std::string name() const { return "apple"; }
};
|
72,010,108 | 72,014,842 | Jsoncpp nested arrays of objects | I need to search for an element in a json file using the jsoncpp library.
I can't wrap my head around how to get to the most inner array... Any thoughts?
{
"key": int,
"array1": [
{
"key": int,
"array2": [
{
"key": int,
"array3": [
{
"needed_key": int
}
]
}
]
}
]
}
Up until now I tried something like this:
const Json::Value& array1 = root["array1"];
for (size_t i = 0; i < array1.size(); i++)
{
const Json::Value& array2 = array1["array2"];
for (size_t j = 0; j < array2.size(); j++)
{
const Json::Value& array3 = array2["array3"];
for (size_t k = 0; k < array3.size(); k++)
{
std::cout << "Needed Key: " << array3["needed_key"].asInt();
}
}
}
But it throws:
JSONCPP_NORETURN void throwLogicError(String const& msg) {
throw LogicError(msg);
}
| You can't access array2 with array1["array2"], since array1 contains an array of objects, not an object, so you should get array2 with an index i, array1[i]["array2"] instead.
The following code works for me:
const Json::Value &array1 = root["array1"];
for (int i = 0; i < array1.size(); i++) {
const Json::Value &array2 = array1[i]["array2"];
for (int j = 0; j < array2.size(); j++) {
const Json::Value &array3 = array2[j]["array3"];
for (int k = 0; k < array3.size(); k++) {
std::cout << "Needed Key: " << array3[k]["needed_key"].asInt();
}
}
}
The output looks like:
Needed Key: 4
|
72,010,284 | 72,034,562 | Is this a safe / correct implementation of a variadic list argument used to simplify setting "pinMode"? | Code (C++):
I'm new to C++ so I'm not sure if this is safe:
#include <Arduino.h>
void pin_mode(uint8_t pins[], uint8_t mode) {
const int length = *(&pins + 1) - pins;
for (size_t i = 0; (signed)i < length; i++) {
pinMode(pins[i], mode);
}
}
I have multiple pins that have the same pin setting, I'd like to set their values on one line instead of having 12 + lines that call the same function.
Usage:
pin_mode([PIN_1, PIN_2, PIN_3, PIN_4], OUTPUT);
Is this a safe / correct implementation?
| If I were doing this, I'd pass the array by reference, so the compiler would compute its size for me:
#include <Arduino.h>
template <size_t N>
void pin_mode(uint8_t (&pins)[N], uint8_t mode) {
for (size_t i = 0; i < N; i++) {
pinMode(pins[i], mode);
}
}
Of course, with this you're free to use a range-based for loop if you prefer.
|
72,010,359 | 72,055,468 | Optional node still visited in OR-tools vehicle routing problem | In a simple vehicle routing problem solved by Google OR-tools library, two nodes (2, 3) are marked as optional with visiting penalty set to 0. The shortest path of distance 2 from the depot to the landfill is 0 -> 1 -> 4, however, the solver ends-up with path 0 -> 2 -> 3 -> 1 -> 4 of distance 4.
Where is the problem? Why the solver insists on the longer path through optional nodes and does not skip them?
#include "ortools/constraint_solver/routing.h"
using namespace operations_research;
struct DataModel {
static constexpr int I = 2;
const std::vector<std::vector<int>> dist {
{ 0, 1, 1, I, I},
{ I, 0, I, 1, 1},
{ I, I, 0, 1, 1},
{ I, 1, 1, 0, I},
{ I, I, I, 1, 0},
};
const RoutingIndexManager::NodeIndex depot{0};
const RoutingIndexManager::NodeIndex landfill{4};
};
void printSolution(const RoutingIndexManager& manager,
const RoutingModel& routing,
const Assignment& solution)
{
if (routing.status() != RoutingModel::Status::ROUTING_SUCCESS)
return;
int index = routing.Start(0);
std::ostringstream route;
while (routing.IsEnd(index) == false) {
route << manager.IndexToNode(index).value() << " -> ";
index = solution.Value(routing.NextVar(index));
}
LOG(INFO) << route.str() << manager.IndexToNode(index).value();
LOG(INFO) << "Problem solved in " << routing.solver()->wall_time() << "ms";
}
int main(int /*argc*/, char** /*argv*/)
{
DataModel data;
RoutingIndexManager manager(data.dist.size(), 1, {data.depot}, {data.landfill});
RoutingModel routing(manager);
const int callback = routing.RegisterTransitCallback(
[&data, &manager](int from_index, int to_index) -> int {
auto from_node = manager.IndexToNode(from_index).value();
auto to_node = manager.IndexToNode(to_index).value();
return data.dist[from_node][to_node];
});
routing.SetArcCostEvaluatorOfAllVehicles(callback);
// make nodes 2, 3 optional
routing.AddDisjunction({manager.NodeToIndex(RoutingIndexManager::NodeIndex(2))}, 0, 1);
routing.AddDisjunction({manager.NodeToIndex(RoutingIndexManager::NodeIndex(3))}, 0, 1);
const Assignment* solution = routing.Solve();
printSolution(manager, routing, *solution);
return 0;
}
Interestingly, for I = 1, the correct solution 0 -> 1 -> 4 is found. However, such dist matrix is trivial.
| This was answered on the or-tools-discuss mailing list.
You encountered a corner case for the default parameter setup. Thanks for forwarding this, we will work on a proper fix.
To work around the problem, you can modify the default parameters as follows:
Option 1 - activate make_chain_inactive - faster option
RoutingSearchParameters search_parameters = DefaultRoutingSearchParameters();
search_parameters.mutable_local_search_operators()->set_use_make_chain_inactive(OptionalBoolean::BOOL_TRUE);
const Assignment* solution = routing.SolveWithParameters(search_parameters);
Option 2 - activate inactive_lns - slower option but slightly more generic
RoutingSearchParameters search_parameters = DefaultRoutingSearchParameters();
search_parameters.mutable_local_search_operators()->set_use_inactive_lns(OptionalBoolean::BOOL_TRUE);
const Assignment* solution = routing.SolveWithParameters(search_parameters);
|
72,010,370 | 72,010,598 | Why my program is terminated but main thread is run? | I run thread in Qmainwindow using thread library not qthread
I not use thread.join but main thread is run but program is terminated
why program is temianted?
void MainWindow::onSendMsg()
{
// std::thread trdSend([this](){
socket = new QTcpSocket(this);
socket->connectToHost(clientIP,clientPort.toUInt());
//socket->close();
QLabel *lblMsg = new QLabel;
QByteArray data;
qDebug()<<"New Message";
if(filePath.isNull() || filePath.isEmpty())
{
qDebug()<<"Message is Text";
QString msg=leMsg->text();
qDebug()<<"Message : "<< msg;
data =msg.toUtf8();
data.insert(0,'0');
qDebug()<<"Add Flag To Message";
//lblMsg->setText(msg);
qDebug()<<"Message Is Ready";
socket->write(data);
std::thread trdSend((Send()),&data);
//trdSend.join();
emit addWidget(true,true,data);
}
| Literally from std::thread::~thread:
~thread(); (since C++11)
Destroys the thread object.
If *this has an associated thread (joinable() == true), std::terminate() is called.
Notes
A thread object does not have an associated thread (and is safe to destroy) after
it was default-constructed
it was moved from
join() has been called
detach() has been called
The instance std::thread trdSend; is created as local variable.
After the emit addWidget(true,true,data); the scope is left and the trdSend is destroyed while none of the four conditions is met.
|
72,010,460 | 72,010,521 | why this template function does not recognize the lamda's returned type? | This template function does not recognize the lamda's returned type, even specifing it decommenting '->void'.
Why does it happen?
What could I do to circumvent this problem?
#include<iostream>
#include<array>
template<typename T, typename S, size_t SIZE>
void for_each(std::array<T,SIZE>& arr, S(*func)(int&))
{
for (auto i{0}; i != arr.size(); ++i)
func(arr[i]);
}
int main()
{
std::array<int, 5> five_elems{10, 20, 30, 40, 50};
for_each(five_elems, [](int& ref)/*->void*/{ref *= 2; std::cout << ref << ' '; });
//for (auto i : five_elems)
// i*=2;
for (const auto i : five_elems)
std::cout << i << ' ';
}
| Your for_each expects a function pointer, but the implicit conversion (from lambda to function pointer) won't be considered in template argument deduction, which causes the calling failing.
You can perform the conversion explicitly:
for_each(five_elems, static_cast<void(*)(int&)>([](int& ref)/*->void*/{ref *= 2; std::cout << ref << ' '; }));
Or
for_each(five_elems, +[](int& ref)/*->void*/{ref *= 2; std::cout << ref << ' '; });
Or just stop using the function pointer parameter. You can add a new type template parameter and then the lambda directly.
template<typename T, size_t SIZE, typename F>
void for_each(std::array<T,SIZE>& arr, F func)
{
for (auto i{0}; i != arr.size(); ++i)
func(arr[i]);
}
|
72,010,604 | 72,011,069 | Is there a C++ STL function to compare a value against a compile-time constant? | I've implemented the following function in a utility library:
template <auto Value>
bool equals_constant(const decltype(Value)& value) { return Value == value; }
It's useful with other template functions which take an invocable predicate, like this:
template <auto IsValid>
struct Validator {
bool validate(int value) { return IsValid(value); }
};
// this validator requires its value to equal 42 (just for demo purposes)
Validator<equals_constant<42>> validator;
std::cout << validator.validate(41) << std::endl; // 0
std::cout << validator.validate(42) << std::endl; // 1
Have I reinvented the wheel - is something like my equals_constant() already in the STL? (If so, I can't find it on cppreference or Google.) Thanks.
| No. std isn't a place where "anything vaguely useful" gets put.
boost::hana::equal.to looks to be similar.
|
72,012,706 | 72,012,924 | What is the preferred way to write string to file in C++, use '+' or several '<<'? | I am considering writing several lines into a file in C++ using ofstream and the text is composed of several parts (strings and numbers), so essentially I know there are two ways.
Here is a simple example:
// Way 1 (Use several '<<')
f << str1 << " " << 10 << "Text" << std::endl;
// Way 2 (Use plus to have a continuous string)
f << str1 + " " + std::to_string(10) + "Text" << std::endl;
So which one is preferred (or maybe use append instead of +) in terms of efficiency and other criteria?
| I wrote a small program that tries both methods, the first version, using << seems to be faster. In any case, the usage of std::endl inhibits performance significantly, so I've changed it to use \n.
#include <iostream>
#include <fstream>
#include <chrono>
int main () {
unsigned int iterations = 1'000'000;
std::string str1 = "Prefix string";
std::ofstream myfile;
myfile.open("example.txt");
auto start = std::chrono::high_resolution_clock::now();
for (int i=0; i < iterations; i++) {
myfile << str1 << " " << 10 << "Text" << "\n";
}
auto stop = std::chrono::high_resolution_clock::now();
auto duration = stop - start;
std::cout << "Duration: " << duration.count() << std::endl;
std::ofstream myfile2;
myfile2.open("example2.txt");
start = std::chrono::high_resolution_clock::now();
for (int i=0; i < iterations; i++) {
myfile2 << str1 + " " + std::to_string(10) + "Text" << "\n";
}
stop = std::chrono::high_resolution_clock::now();
duration = stop - start;
std::cout << "Duration: " << duration.count() << std::endl;
myfile.close();
return 0;
}
And the output on my machine:
Duration: 91549609
Duration: 216557352
|
72,013,343 | 72,013,580 | Using Boost strong typedef with unordered_map | I am using a Boost strong typedef to strong-type uint64_t:
BOOST_STRONG_TYPEDEF(uint64_t, MyInt)
and an std::unordered_map using this:
std::unordered_map<MyInt, int> umap;
Unfortunately I get a lot of compiler errors (can't paste here as they're on another machine):
error: static assertion failed: hash function must be invocable with an argument of key type
.static_assert(__is_invocable<const _H1&, const _Key&>)
error: use of deleted function 'std::__detail::_Hashtable_ebo_helper
_Hashtable() = default;
(+ a lot more I cannot type)
Using a Boost strong type as the key definitely causes the problem because if I remove the unordered_map I get no compiler errors.
| From the boost documentation about BOOST_STRONG_TYPEDEF, it is clearly mentioned that it defines a new type wrapping the target inner type (it is not a simple alias).
Knowing that, there is no defined std::hash<MyInt> specialization available (required by std::unordered_map<MyInt, int>) since MyInt is now a distinct type from uint64_t.
You just need to provide one and it should work as expected.
For instance:
namespace std
{
template <>
struct hash<MyInt>
{
size_t operator()(const MyInt & m) const
{
return hash<uint64_t>{}(m);
}
};
}
Edit:
As pointed out in comments, you could also directly pass the proper std::hash<> specialization to use from the std::unordered_map<> instantiation as the third template parameter since MyInt is implicitly convertible to uint64_t (as mentioned in the boost documentation as well).
It would then become:
std::unordered_map<MyInt, int, std::hash<uint64_t>> umap;
No need to define your own std::hash<MyInt> specialization anymore.
|
72,013,873 | 72,610,580 | DocuSign JSON SOAP Request | I am trying to understand how to send SOAP requests with JSON formatted data to docusign. Following this guide is only for pdfs:
https://developers.docusign.com/docs/esign-soap-api/how-to/request-signature/
I created a template on docusign developer and downloaded it, which is in json format.
How do I send the data in that format? Is it currently stored as documentBase64, do I need to convert it the data to a PDF, or just set the documents bytes to that value (doc.PDFBytes)? Attempting to do the ladder, gives me a soap error:
Soap Fault: The validation of the PDF file failed.
What fields are required to pull out of the json at minimum?
Yes, I have the envelope, recipient and tabs set up. I currently am able to send PDFs as is to get signed, just not json formatted data.
Here is an example of attempting to pull out the documentbase64 data and set it to the pdfbytes field:
string pdfbytes = json4.value("documentBase64", "oops");
doc->PDFBytes = new xsd__base64Binary();
size_t pdfSize = 0;
// Double conversion to get it to match the datatype for *PDFBytes->ptr*
const unsigned char* t = reinterpret_cast<const unsigned char *>( pdfbytes.c_str() );
unsigned char* y = const_cast<unsigned char*>(t);
doc->PDFBytes->__ptr = y;
doc->PDFBytes->__size = pdfbytes.size();
UPDATE:
Solved my own problem. You will need to decode your base64 data from docusign. I used the following decoder:
https://renenyffenegger.ch/notes/development/Base64/Encoding-and-decoding-base-64-with-cpp/
Updated code:
string pdfbytes = json4.value("documentBase64", "oops");
std::string decoded = base64_decode(pdfbytes);
| Unless you have a really good reason, I highly recommend you consider using the DocuSign eSignature REST API and not the DocuSign eSignature SOAP API.
Not every feature is supported by the SOAP API.
You could use https://github.com/jgaa/restc-cpp to make REST API calls from a C++ codebase.
Also, remember that documents sent in the API has to be base64 encoded. This goes for both REST and SOAP.
|
72,014,691 | 72,014,747 | How to ignore text case while comparing two strings in C++? | I am a beginner coder. I am trying to create a program which will compare two strings alphabetically. But It will ignore the text case. I am facing problem on it. How can I ignore the text case in C++?
#include <iostream>
using namespace std;
int main() {
string a, b;
cin >> a;
cin >> b;
if ( a > b) {
cout << "1";
}
else if ( a < b) {
cout << "-1";
}
else if (a == b) {
cout << "0";
}
}
| You can convert both strings to lower case before the comparison via std::tolower:
for (auto& c : a) c = std::tolower(static_cast<unsigned char>(c));
for (auto& c : b) c = std::tolower(static_cast<unsigned char>(c));
|
72,014,935 | 72,015,467 | Why does a two-dimensional array become a one-dimensional array after passing it to a function?(C++ | I'm making a simple Snake game. When making a map, my definition of the map is as follows
int map[25][25] = { 0 };
for (int i = 0; i < 25; i++)//Set the boundary to - 2
{
map[0][i] = -2;
map[24][i] = -2;
}
for (int i = 1; i < 25; i++)//Set the boundary to - 2
{
map[i][0] = -2;
map[i][24] = -2;
}
Then I made a function to simulate the motion of the snake。(The first parameter is the class I created: snake,The second is its moving direction. The key is the third parameter, the map array I put in.)
void snake_move(Snake snake1, int direction, int map[][25])
Then I made a call to the function.(The third parameter is the two-dimensional array pointer I passed in)
snake_move(snake1, direction, map);
Then the following figure appears
I found that it was a two-dimensional array before the function call,which is as follows
Why does this happen and how to solve this problem? I look forward to your reply・v・
| You cannot pass built-in arrays like this to functions. snake_move(), even though it appears to have an argument that looks like a 2D array, it actually takes a pointer to a 1D array. This:
void func(int map[][25]);
Is actually equivalent to:
void func(int (*map)[25]);
map is a pointer to an array of 25 int elements. When you call that function:
func(map);
The map array "decays" to a pointer that points to its first element.
This is an unfortunate consequence of C++'s compatibility with C.
To avoid issues like this, use std::array (for fixed-size, static allocation of elements), or std::vector (for dynamically allocated elements.)
To get a 2D array, you need to use an array of arrays or a vector of vectors. For an array, that means:
std::array<std::array<int, 25>, 25>
This means "an array containing 25 arrays of 25 int elements.
It's a good idea to make snake_move take a const reference to avoid an unnecessary copy of the whole array. So:
#include <array>
void snake_move(
Snake snake1, int direction,
const std::array<std::array<int, 25>, 25>& map);
// ...
std::array<std::array<int, 25>, 25> map{};
for (int i = 0; i < 25; i++) {
map[0][i] = -2;
map[24][i] = -2;
}
for (int i = 1; i < 25; i++) {
map[i][0] = -2;
map[i][24] = -2;
}
snake_move(snake1, direction, map);
If snake_move() needs to modify the passed array, then remove the const.
To reduce the need to write the type over and over again, you can use an alias (with the using keyword):
using MapType = std::array<std::array<int, 25>, 25>;
void snake_move(Snake snake1, int direction, const MapType& map);
// ...
MapType map{};
// ...
The {} in the map declaration will initialize all values to zero. You can also use:
MapType map = {};
which does the same.
|
72,015,309 | 72,016,334 | Serialize openDDS topic to a `std::string` | I've using OpenDDS in a project. Now, for interoperability, we need to send topics also with a custom framework to other machines. Since this custom framework allows to send strings, I'd like to serialize the topics in a string and then send them.
I was using boost::serialization, but then I've made up the idea that in order to send a topic, OpenDDS should be able to serialize a topic some way, so I should be able to pick the corresponding function and use it for serialize data.
Inspecting the code I was able to find the overload of >>= and <<= operators:
void
operator<<= (
::CORBA::Any &_tao_any,
BasicType::LocalForceDataDataReader_ptr _tao_elem)
{
BasicType::LocalForceDataDataReader_ptr _tao_objptr =
BasicType::LocalForceDataDataReader::_duplicate (_tao_elem);
_tao_any <<= &_tao_objptr;
}
/// Non-copying insertion.
void
operator<<= (
::CORBA::Any &_tao_any,
BasicType::LocalForceDataDataReader_ptr *_tao_elem)
{
TAO::Any_Impl_T<BasicType::LocalForceDataDataReader>::insert (
_tao_any,
BasicType::LocalForceDataDataReader::_tao_any_destructor,
BasicType::_tc_LocalForceDataDataReader,
*_tao_elem);
}
It serializes the topic into Corba::Any. It seems to work, but now I need to send the content of Corba::Any. Is there a way to put the content of Corba::Any to a string, and retrieve its data from a string? Or, in other words, how can I serialize and deserialize Corba::Any?
Or there's a better way to serialize a OpenDDS topic to a string?
| It's possible to use TAO's serialization system to do this, but it's probably better to use what OpenDDS is using: https://github.com/objectcomputing/OpenDDS/blob/master/dds/DCPS/Serializer.h (or at least it's easier for me to write an example for since I know it much better)
These are some functions that will serialize types to and from std::strings:
const OpenDDS::DCPS::Encoding encoding(OpenDDS::DCPS::Encoding::KIND_XCDR2);
template <typename IdlType>
std::string serialize_to_string(const IdlType& idl_value)
{
const size_t xcdr_size = OpenDDS::DCPS::serialized_size(encoding, idl_value);
ACE_Message_Block mb(xcdr_size);
OpenDDS::DCPS::Serializer serializer(&mb, encoding);
if (!(serializer << idl_value)) {
throw std::runtime_error("failed to serialize");
}
return std::string(mb.base(), mb.length());
}
template <typename IdlType>
IdlType deserialize_from_string(const std::string& xcdr)
{
ACE_Message_Block mb(xcdr.size());
mb.copy(xcdr.c_str(), xcdr.size());
OpenDDS::DCPS::Serializer serializer(&mb, encoding);
IdlType idl_value;
if (!(serializer >> idl_value)) {
throw std::runtime_error("failed to deserialize");
}
return idl_value;
}
Also be careful when using std::string for any binary data like CDR to make sure it's not interpreted as a null-terminated string.
|
72,015,959 | 72,016,033 | Correct way to instantiate a class member of template class with paramter | I have a template class with an instantiation parameter.
I have another class that has a member parameter of that class.
The follow does not compile because it says instantiation method is deleted...
class MyClass {
public:
MyTClass<AClass> tclass;
}
The following works but I am not sure if it is the correct way...
class MyClass {
public:
MyTClass<AClass> tclass = MyTClass<AClass>(1234);
}
It seems the member paramter is instantiated but is it tidied up on owner class destruction?
I wish to avoid new and delete if I can to keep my code tidy so I am thinking I wish to take advantance of member parameter instantiation on class instantiation. As I have added explicit instantiation, do I need to fall back to new and delete to ensure it is destructed?
| No, you do not need to do anything extra here. The destructor of MyClass invokes the destructor of all members, regardless of how they were originally constructed.
(This is true even if the member is a pointer. But the destructor of a pointer does nothing, which is why you'd need a delete call to destruct and free the thing it points to.)
|
72,016,205 | 72,017,989 | DPC++ & MPI, buffer, shared memory, variable declare | I am new to DPC++, and I try to develop a MPI based DPC++ Poisson solver. I read the book and am very confused about the buffer and the pointer with the shared or host memoery. What is the difference between those two things, and what should I use when I develop the code.
Now, I use the buffer initialized by an std::array with const size for serial code and it works well. However when I couple the DPC++ code with MPI, I have to declare a local length for each device, but I fail to do that. Here I attach my code
define nx 359
define ny 359
constexpr int local_len[2];
global_len[0] = nx + 1;
global_len[1] = ny + 1;
for (int i = 1; i < process; i++)
{
if (process % i == 0)
{
px = i;
py = process / i;
config_e = 1. / (2. * (global_len[1] * (px - 1) / py + global_len[0] * (py - 1) / px));
}
if (config_e >= cmax)
{
cmax = config_e;
cart_num_proc[0] = px;
cart_num_proc[1] = py;
}
}
local_len[0] = global_len[0] / cart_num_proc[0];
local_len[1] = global_len[1] / cart_num_proc[1];
constexpr int lx = local_len[0];
constexpr int ly = local_len[1];
queue Q{};
double *m_cellValue = malloc_shared<double>(size, Q);
I got the error
error: default initialization of an object of const type 'const int[2]'
error: cannot assign to variable 'local_len' with const-qualified type 'const int[2]'
main.cpp:52:18: error: cannot assign to variable 'local_len' with const-qualified type 'const int[2]'
Is there any way to just define a variable size array to do the parallel for in DPC++?
| You are too eager in using constexpr. Remove all three occurrences in this code, and it should compile. So this has nothing to do with DPC++.
|
72,016,461 | 72,023,533 | RDMA Read protection for local memory operations | I have the following scenario: My server allocates a buffer of 1MB, which is periodically updated and written to (about every 50ms). The client is connected to the the server via Infiniband and periodically reads that buffer via RDMA Read (potentially even faster than it is updated).
My question is: Is there any way to ensure that the local write operation is atomic so that the RDMA read can only read valid and contiguous memory?
Did I correctly understand that the memory regions are only protected from parallel RDMA operations, but not local memory operations? Is there any way to accomplish this behaviour natively with the ibverbs API?
| The answer may depend on the device. In RDMA Verbs, there are two different modes for atomic operation (which can be checked using the ibv_query_device verb). With IBV_ATOMIC_HCA, atomic operations are only atomic with respect to other operations from the same device, while IBV_ATOMIC_GLOB means that they are atomic also with respect to CPU operations and other RDMA devices.
If a device uses IBV_ATOMIC_HCA, you need to synchronize the RDMA reads with the CPU writes to ensure data consistency.
|
72,018,146 | 72,018,214 | C++ custom assignment | I have the following code:
template<size_t rows, size_t cols>
class Matrix{
std::array<int, rows * cols> data;
public:
int operator()(size_t i, size_t j){
return data[i * cols + j];
}
// ...code...
}
What is the best way to achieve this:
Matrix<1,1> a;
a(0, 0) = 0;
avoiding the lvalue required as left operand of assignment error?
| You can change the following line:
int operator()(size_t i, size_t j){
To:
int & operator()(size_t i, size_t j){
Returning a refernce (L value reference to be precise) to the element in the Matrix will allow you to assign to it.
Update: Some notes to complete my answer:
As @user4581301 commented: you can see more info about C++ value categories here: What are rvalues, lvalues, xvalues, glvalues, and prvalues?
As @Darth-CodeX and @HolyBlackCat mentioned, it is advisable to add a const overload for operator():
int const & operator()(int i, int j) const { /* same implementation */ }
You can use it with a const Matrix for reading elements values: if you have e.g. a Matrix const & m, you can use int val = m(0,0) to read an element value (of cource you will not be able to use it for assignment due to constness).
|
72,018,553 | 72,020,749 | Win32 window not showing when ran through CLI/VSCode debugger | I am creating a Win32 application, I have followed some setup code for creating a Win32 window without the need for a WinMain which can be found here. The code builds just fine and if I run the application by opening it in a file browser it runs no problem. However, if I run it via the command line it only outputs the console logs and doesn't create a window. I assume that this is also why if I run it via VSCode's debugger it also doesn't launch a window. Has anyone come across this issue before and found a fix for it? It would be pretty had to debug a GUI application if you can't use the debugger and see it at the same time.
| This bit of code contains a mistake:
STARTUPINFO si;
GetStartupInfo(&si);
int nCmdShow = si.wShowWindow;
You forgot to check si.dwFlags, as indicated in the documentation for wShowWindow:
If dwFlags specifies STARTF_USESHOWWINDOW, this member can be any of the values that can be specified in the nCmdShow parameter for the ShowWindow function, except for SW_SHOWDEFAULT. Otherwise, this member is ignored.
|
72,018,885 | 72,032,419 | print condition while integer overflow not working | #include <iostream>
using namespace std;
int getFectorial(int n)
{
int ans = 1;
for (int i = n; i >= 1; i--)
{
ans = ans * i;
}
return ans;
}
int printNcr(int n, int r)
{
if (getFectorial(n) > INT_MAX)
{
return 0;
}
return (getFectorial(n)) / ((getFectorial(r)) * (getFectorial(n - r)));
}
int main()
{
int n = 14;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < row + 1; col++)
{
cout << printNcr(row, col) << " ";
}
cout << endl;
}
return 0;
}
When I give value of n more than 13th I want integer overflow condition should be working that given in printNcr() function, but it's not working and all line after 13th are printing wrong values instead of returning false.
How to make given INT_MAX condition work?
| int oveflow cannot be reliably detected after it happens.
One way to detect upcoming int overflow in factorial:
int getFactorial(int n) {
if (n <= 0) {
return 1; // and maybe other code when n < 0
}
int limit = INT_MAX/n;
int ans = 1;
for (int i = 2; i <= n; i++) {
if (ans >= limit) {
return INT_MAX; // Or some other code
}
ans = ans * i;
}
return ans;
}
Another way is at startup, perform a one-time calculation for maximum n. With common 32-bit int, that limit is 12.
int getFactorial(int n) {
if (n > getFactorial_pre_calculated_limit) {
return INT_MAX;
}
...
|
72,018,905 | 72,019,970 | C++ multidimensional array on heap | I don't understand how to create an multidimensional array on the heap with the new operator. In java it works like that:
int[][][] array = new int[3][3][3];
how do I achieve the same thing in c++? I wanna have an 3d array that I can access like that:
array[0][0][0] = 1;
How can I do that?
| Generally as you mentioned in the comments stack space is limited. In a lot of cases this does not really matter and most definitely it is not a problem for an int array that essentially has size in the double digits. To have it on the stack you can just do:
int array[3][3][3];
Note that this only works if 3 is known compile time. This has the benefit that it is incredibly fast and not really much trouble for you the programmer.
The second option is actually allocating on the heap. The naive way of doing this is:
int*** array = new int**[3];
for (size_t i = 0; i < 3; ++i) {
array[i] = new int*[3];
for (size_t j = 0; j < 3; ++j)
array[i][j] = new int[3];
}
with of course delete[], when we are done with the memory like:
for (size_t i = 0; i < 3; ++i) {
for (size_t j = 0; j < 3; ++j)
delete[] array[i][j];
delete[] array[i];
}
delete[] array;
The good thing about this is that 3 here does not have to be compile time, but this suffers greatly from the slowness of new. This second problem can be offset by using a trick like:
int* data = new int[3*3*3];
int** helper_array = new int*[3*3];
int*** array = new int**[3];
for (size_t i = 0; i < 3; ++i)
array[i] = helper_array + 3*i;
for (size_t i = 0; i < 3; ++i)
for (size_t j = 0; j < 3; ++j)
helper_array[3*i + j] = data + 3*3*i + 3*j;
with the obligatory release of memory:
delete[] array;
delete[] helper_array;
delete[] data;
This is much easier and nicer to handle, and it also suffers less from the slow speed of new, while still retaining the array[i][j][k] data access.
The easiest way however to handle dynamic memory is through some container like std::vector<>:
std::vector<std::vector<std::vector<int>>> array(3, std::vector<std::vector<int>>(3, std::vector<int>(3)));
This has the benefits that the memory is no longer managed by you, but it still allows for data that has length unknown at compile time. It also does not store data on the stack (unless you explicitly make it do that), so you don't have to worry about stack space running out, but it will have the slow down of the int*** array = new int**[3] solution. An other drawback is that this solution can become very messy at multiple nested vectors.
While the solutions presented here are perfectly valid for some other solutions involving more modern approaches to C++ see n. 1.8e9-where's-my-share m.'s answer. Those don't open up the possibility of memory leaks and usually are much more nice to manage them because of this.
|
72,019,389 | 72,019,491 | How to get data from hookproc function winapi (C++) | I have a program that sets a hook on another window. I want this program to know if my hook function received a message. How can I do it?
I've had an idea to send message from hook function to my main window, but I don't know how to pass the HWND handler. Also I don't want to use EnumWindows or FindWindow to find my main window.
| The simplest solution is to store your target HWND in shared memory that both the main program and the hook can access.
If your compiler supports #pragma data_seg() (ie, MSVC), you can use that to declare an HWND variable in a shared code section in a DLL. Have your main program and your hook use the same DLL. See Process shared variable #pragma data_seg usage.
Otherwise, you can use CreateFileMapping()+MapViewOfFile() to allocate a block of memory at runtime, and then store/read the HWND value from it. See Creating Named Shared Memory.
Either way, the main program can then assign the shared hwnd, and the hook can read it.
|
72,019,875 | 72,022,926 | Usage of alignas in template argument of std::vector | I want to create a std::vector with doubles. But these doubles should be aligned in 32 byte for AVX2 registers. What would be the best way to do this? Can I simply write something like
std::vector<alignas(32)double>?
Thanks in advance for the help.
| If alignas(32)double compiled, it would require that each element separately had 32-byte alignment, i.e. pad each double out to 32 bytes, completely defeating SIMD. (I don't think it will compile, but similar things with GNU C typedef double da __attribute__((aligned(32))) do compile that way, with sizeof(da) == 32.)
See Modern approach to making std::vector allocate aligned memory for working code.
As of C++17, std::vector<__m256d> would work, but is usually not what you want because it makes scalar access a pain.
C++ sucks for this in my experience, although there might be a standard (or Boost) allocator that takes an over-alignment you can use as the second (usually defaulted) template param.
std::vector<double, some_aligned_allocator<32> > still isn't type-compatible with normal std::vector, which makes sense because any function that might reallocated it has to maintain alignment. But unfortunately that makes it not type-compatible even for passing to functions that only want read-only access to a std::vector of double elements.
Cost of misalignment
For a lot of cases the misalignment is only a couple percent worse than aligned, for AVX/AVX2 loops over an array if data's coming from L3 cache or RAM (on recent Intel CPUs); only with 64-byte vectors do you get a significantly bigger penalty (like 15% or so even when memory bandwidth is still the bottleneck.) You'd hope that the CPU core would have time to deal with it and keep the same number of outstanding off-core transactions in flight. But it doesn't.
For data hot in L1d, misalignment could hurt more even with 32-byte vectors.
In x86-64 code, alignof(max_align_t) is 16 on mainstream C++ implementations, so in practice even a vector<double> will end up aligned by 16 at least because the underlying allocator used by new always aligns at least that much. But that's very often an odd multiple of 16, at least on GNU/Linux. Glibc's allocator (also used by malloc) for large allocations uses mmap to get a whole range of pages, but it reserves the first 16 bytes for bookkeeping info. This is unfortunate for AVX and AVX-512 because it means your arrays are always misaligned unless you used aligned allocations. (How to solve the 32-byte-alignment issue for AVX load/store operations?)
Mainstream std::vector implementations are also inefficient when they have to grow: C++ doesn't provide a realloc equivalent that's compatible with new/delete, so it always has to allocate more space and copy to the start. Never even trying to allocate more space contiguous with the existing mapping (which would be safe even for non-trivially-copyable types), and not using implementation-specific tricks like Linux mremap to map the same physical pages to a different virtual address without having to copy all those mega/gigabytes. The fact that C++ allows code to redefine operator new means library implementations of std::vector can't just use a better allocator, either. All of this is a non-problem if you .reserve the size you're going to need, but it is pretty dumb.
|
72,019,913 | 72,019,947 | How to Convert e.x. 2/3 or 1/2 in input to float in cpp | How to Convert e.x. 2/3 or 1/2 in input to float in cpp
string s="2/3";
float x=stod(s);
| You could try something like:
int a,b;
string s="2/3";
sscanf(s.c_str(), "%d/%d", &a, &b);
float x = float(a)/b;
Of course, you have to do some validations around b being zero.
|
72,019,994 | 72,020,497 | Is there a way to build a project with multiple C++ files efficiently in Visual Studio Code? | I have a project in Visual Studio code with > 10 .cpp files. The reason they're split up this way was to make compilation faster, and it is faster in Visual Studio 2022. However, when using a build task in Visual Studio Code that simply includes all .cpp files it can find, it obviously compiles really slowly, as expected. But, is there a way it can compile individual .cpp files into object files, and link them at the end, only recompiling each .cpp file if it's contents have changed?
Also, I'm running Windows.
| Solution: Use CMake. It's less complicated and more reliable than Visual Studio build tasks. Comments on my original question clear up how that's done.
|
72,020,221 | 72,020,530 | How can i write an array starting from right to left in C++ | I don't want to reverse or shift the array. What I want is to write the array from right to left.
I did something like
int arr[5] = {0};
for (int i = 0; i < 5; i++)
{
cout << "enter a number : ";
cin >> arr[i];
for (int j = 0; j < 5; j++)
{
if (arr[j] != 0)
{
cout << arr[j] << " ";
}
else
cout << "X ";
}
cout << endl;
}
and on the output screen I see this
enter a number : 5
5 X X X X
enter a number : 4
5 4 X X X
enter a number : 3
5 4 3 X X
enter a number : 2
5 4 3 2 X
enter a number : 1
5 4 3 2 1
Press any key to continue . . .
but i want to see this
enter a number : 5
X X X X 5
enter a number : 4
X X X 5 4
enter a number : 3
X X 5 4 3
enter a number : 2
X 5 4 3 2
enter a number : 1
5 4 3 2 1
Press any key to continue . . .
how can I do that?
I will be glad if you help.
| Just change the inner for loop for example the following way
int j = 5;
for ( ; j != 0 && arr[j-1] == 0; --j )
{
std::cout << 'X' << ' ';
}
for ( int k = 0; k != j; k++ )
{
std::cout << arr[k] << ' ';
}
|
72,020,517 | 72,020,819 | Why can't the compiler ever elide the vtable? | Sometimes I create an abstract class merely for implementation hiding, as an alternative to the pimpl idiom. If there is only one descendant and no public visibility outside the library that I'm building, why can't the linker remove the vtable?
I tried some experiments with clang and -Os. I added this to the constructor of one of my private impl classes:
printf("%p vs %p\n", this, &_first_member_field);
I always see an 8-byte difference between these two pointers, which I assume is the vtable pointer since I'm on a 64-bit arch. I also tried:
-no-rtti -flto=full -fvirtual-function-elimination -fstrict-vtable-pointers
But those 8 bytes never go away. Is this due to spec compliance?
| Proving that (safely deriived) pointers to instances of your class are never passed to any code the compiler cannot examine is insanely hard.
Once such a pointer is in any code the compiler cannot examine, it must provide a vtable pointer to support RTTI and dynamic dispatch. And this must be ABI compatible with someone else who inherits from your API and implements a different implementation.
You intend there to be exactly one implementation of this interface. But you cannot communicate this to your compiler, so it does not know this.
An example of this is the fact you passed the pointer to printf above. The implementation of printf is opaque to your C++ compiler (at some level of iteration); as far as your compiler knows, the value is cast back to the interface pointer and examined using RTTI. Or passed to some function that consumes the abstract API you specified, and other code passes a different implementation.
Devirtualization, removal of virtual dispatch, and object elimination are things that C++ compilers do when optimizing code. It is plausible such a set of operations could occur; amusingly, attempting to detect offsets of members is the kind of thing that would block these optimizations.
I can write code where created objects don't exist jn the output assembly, and vtable calls are skipped. They aren't going to be fiddling with raw memory, however, because that kind of operation makes optimizers give up.
|
72,020,782 | 72,028,046 | dpc++ start the do loop from 1 to n-2 using parallel_for range | Is that possible to start the do loop and the index is from 1 to n-2 using dpc++ parallel_for?
h.parallel_for(range{lx , ly }, [=](id<2> idx
this will give a do loop from 0 to lx-1, and I have to do
idx[0]>0 && idx[1]>0 && idx[0]<lx-1 && idx[1]<ly-1
and then I can complete the loop?
Also, does dpc++ support like 4D parallel_for?
| In SYCL 1.2.1, parallel_for supports offsets, so you could use h.parallel_for(range{lx-2, ly-2}, id{1, 1}, [=](id<2> idx){ ... });.
However, this overload has been deprecated in SYCL 2020:
Offsets to parallel_for, nd_range, nd_item and item classes have been deprecated. As such, the parallel iteration spaces all begin at (0,0,0) and developers are now required to handle any offset arithmetic themselves. The behavior of nd_item.get_global_linear_id() and nd_item.get_local_linear_id() has been clarified accordingly.
So, if you want to conform to the latest standard, you should apply the offset manually:
h.parallel_for(range{lx-2, ly-2}, [=](id<2> idx0) { id<2> idx = idx0 + 1; ... });
That said, depending on your data layout, your original approach of having "empty" threads might be faster.
Also, does dpc++ support like 4D parallel_for?
No. You will have to use 1D range and compute the 4D index manually.
|
72,021,092 | 72,021,170 | recv() fails to read last chunk | The function below reads incoming data perfectly but only if the last data chunk is smaller than BUFFSIZE. If the size of the last buff happens to be equal to BUFFSIZE, then the program tries to recv again in the next loop iteration and sets bytes to 1844674407379551615 (most probably integer overflow) and repeats this in an infinite loop... Why? Why isn't it 0? And why doesn't it escape the loop at this stage?
std::string getMsg (int clientFileDescriptor, int timeout_sec)
{
std::string msg;
msg.reserve(BUFFSIZE * 10);
char buff[BUFFSIZE + 1];
signal(SIGPIPE, SIG_IGN);
//set a timeout for reading and writing
struct timeval tv;
tv.tv_sec = timeout_sec;
tv.tv_usec = 0;
setsockopt (clientFileDescriptor, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));
while (true)
{
size_t bytes = recv (clientFileDescriptor, buff, BUFFSIZE, 0);
std::cout << "bytes read: " << bytes << std::endl;
if (0 < bytes && bytes <= BUFFSIZE)
{
msg.append(buff, bytes);
//'buff' isn't full so this was the last chunk of data
if (bytes < BUFFSIZE)
break;
}
else if (!bytes) //EOF or socket shutdown by the client
{
break;
}
else
{
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
continue;
//We cannot continue due to other erros (e.g. EBADF/socket not available)
break;
}
}
return msg;
}
| Probably size_t is unsigned on your platform. So if the recv times out, recv returns -1 and bytes overflows. Your code doesn't correctly handle this case due to the overflow.
This is just wrong:
//'buff' isn't full so this was the last chunk of data
It's entirely possible buff wasn't full because the last chunk of data hadn't been received yet. Tou should actually add code to detect the end of a message rather than relying on a timeout to find it for you if your application protocol supports messages of different sizes.
Unfortunately, you haven't given us the code for the other end of the connection nor specified how your application protocol works, so I have no idea what the other side does or expects. So it's not possible to give you more useful suggestions.
|
72,021,185 | 72,021,322 | Output operator is not producing expected outcome | I am implementing a class Polynomial with private members consisting of a singly linked list for its coefficient and an int representing the highest degree. The constructor takes in a vector which represents the coefficients in the polynomial. This is my implementation of the constructor and the output operator.
#include <iostream>
#include <vector>
using namespace std;
struct Node{
Node(int data = 0, Node* next = nullptr) : data(data), next(next) {}
int data;
Node* next;
};
class Polynomial{
friend ostream& operator<<(ostream& os, const Polynomial& p);
public:
Polynomial(vector<int> poly){
Node* temp = co;
for(int i : poly){
temp = new Node(i);
temp = temp->next;
}
degree = poly.size() - 1;
}
private:
Node* co;
int degree;
};
ostream& operator<<(ostream& os, const Polynomial& p){
Node* temp = p.co;
int degree = p.degree;
while(temp != nullptr){
if(degree == 1){
os << temp->data << "x" << " ";
}else if(degree == 0){
os << temp->data;
}else{
os << temp->data << "x^" << degree << " ";
}
degree--;
temp = temp->next;
}
return os;
}
When I try to test my code the output was 686588744, which I assume refers to a place in memory, rather than the expected outcome of 17.
int main(){
Polynomial p1({17});
cout << p1;
}
Could anyone point out where I made a mistake in my code?
| This constructor
Polynomial(vector<int> poly){
Node* temp = co;
for(int i : poly){
temp = new Node(i);
temp = temp->next;
}
degree = poly.size() - 1;
}
is invalid. Actually it does not build a list. Instead it produces numerous memory leaks.
For example at first a node was allocated and its address was assigned to the pointer temp and then the pointer was reassigned with the value stored in the data member temp->next that is a null pointer. So the address of the allocated node was lost.
And moreover the pointer co is leaved uninitialized.
You can rewrite it for example the following way
Polynomial( const vector<int> &poly) : co( nullptr ), degree( 0 )
{
Node **current = &co;
for( int i : poly )
{
*current = new Node(i);
current = &( *current )->next;
}
if ( not poly.empty() ) degree = poly.size() - 1;
}
|
72,021,195 | 72,021,596 | How to add/update/delete Department in university class? | #include <iostream>
using namespace std;
class Professor
{
string name;
long employeeID;
string designation;
public:
Professor()
{
name = "";
employeeID = 0;
designation = "";
}
Professor(string n, long ID, string d)
{
name = n;
employeeID = ID;
designation = d;
}
void setProfessorData(string name1, long ID1,string d1)
{
name = name1;
employeeID = ID1;
designation = d1;
}
string getName()
{
return name;
}
long getID()
{
return employeeID;
}
string getDesignation()
{
return designation;
}
};
class Department
{
private:
string name;
long deptID;
Professor profList[5];
int noOfprofessors;
public:
Department()
{
name = "";
deptID = 0;
for (int i = 0; i < 5; i++)
{
profList[i].setProfessorData ("",0,"");
}
noOfprofessors = 0;
}
Department(string name1, long id1, Professor array[5], int no_of_dpt)
{
name = name1;
deptID = id1;
for (int i = 0; i < 5; i++)
{
profList[i] = array[i];
}
noOfprofessors = no_of_dpt;
}
void setDepartmentData(string n, long i, Professor arr[5], int nd)
{
name = n;
deptID = i;
for (int i = 0; i < 5; i++)
{
profList[i] = arr[i];
}
noOfprofessors = nd;
}
string getName1()
{
return name;
}
long getDeptId()
{
return deptID;
}
int getnoOfProfessors()
{
return noOfprofessors;
}
};
class University
{
private:
string name;
Department dept[5];
int numberOfDepartments;
public:
University(string n, Department array[5], int no)
{
name = n;
for (int i = 0; i > 5; i++)
{
dept[i] = array[i];
}
numberOfDepartments = no;
}
void setUniversityData(string name1, Department arr[5], int n1)
{
name = name1;
for (int i = 0; i < 5; i++)
{
dept[i] = arr[i];
}
numberOfDepartments = n1;
}
bool addDepartment(Department D)
{
}
bool deleteDepartment(string name)
{
}
bool updateDepartment(int id, string name)
{
}
};
How to add, delete, and update Department in University class?
I have provided the skeleton code. I have implemented all constructors and destructors, but I don't know how to implement addDepartment(), deleteDepartment(), and updateDepartment()`. Kindly look into this and help me to complete this task.
| First off, several of your for loops are incorrect, namely the ones in the following methods:
Department::Department(string, long, Professor[5], int), should be using no_of_dpt (or better, std::min(no_of_dpt, 5)) instead of 5 for the loop counter.
Department::setDepartmentData(), should be using nd (or better, std::min(nd, 5)) instead of 5 for the loop counter.
University::University(string, Department[5], int), should be using no (or better, std::min(no, 5)) instead of 5 for the loop counter. Also, the loop needs to use < instead of >.
University::setUniversityData(), should be using n1 (or better, std::min(n1, 5)) instead of 5 for the loop counter.
That being said, you already have basic logic for adding elements to arrays, so you can implement addDepartment() by applying that logic correctly, eg:
bool addDepartment(Department D)
{
if (numberOfDepartments < 5)
{
dept[numberOfDepartments] = D;
++numberOfDepartments;
}
}
And, you can easily implement deleteDepartment(), you just need to find the index of the desired Department and shift the remaining departments down 1 element in the array, eg:
bool deleteDepartment(string name)
{
for (int i = 0; i < numberOfDepartments; ++i)
{
if (dept[i].getName1() == name)
{
for(int j = i+1; j < numberOfDepartments; ++j)
{
dept[j-1] = dept[j];
}
--numberOfDepartments;
dept[numberOfDepartments].setDepartmentData("", 0, NULL, 0);
break;
}
}
}
Unfortunately, you cannot implement updateDepartment() with the current code you have shown. This is because University does not have access to update the Department::name field directly, and it does not have access to a Department's existing professor data in order to call Department::setDepartmentData() with just a new name.
So, you will have to fix this issue first, either by making University be a friend of Department, or by adding a Department::setName() setter, or by adding getters for the data in the Department::profList array.
However, once you have addressed that, you can then implement updateDepartment(), eg:
class Department
{
private:
string name;
...
friend class University;
public:
...
};
class University
{
private:
...
public:
...
bool updateDepartment(int id, string newName)
{
for (int i = 0; i < numberOfDepartments; ++i)
{
if (dept[i].getDeptId() == id)
{
dept[i].name = newName;
break;
}
}
}
};
Or:
class Department
{
private:
string name;
...
public:
...
void setName(string newName)
{
name = newName;
}
};
class University
{
private:
...
public:
...
bool updateDepartment(int id, string newName)
{
for (int i = 0; i < numberOfDepartments; ++i)
{
if (dept[i].getDeptId() == id)
{
dept[i].setName(newName);
break;
}
}
}
};
Or:
class Department
{
private:
...
Professor profList[5];
int noOfprofessors;
public:
...
Professor* getProfessors()
{
return profList;
}
int getnoOfProfessors()
{
return noOfprofessors;
}
};
class University
{
private:
...
public:
...
bool updateDepartment(int id, string newName)
{
for (int i = 0; i < numberOfDepartments; ++i)
{
if (dept[i].getDeptId() == id)
{
dept[i].setDepartmentData(newName, dept[i].getDeptId(), dept[i].getProfessors(), dept[i].getnoOfProfessors());
break;
}
}
}
};
|
72,021,473 | 72,156,491 | Save integers from string to vector | I need to save integers from string to vector.
Definition of number: each of strings substrings which consists entirely of digits, with a space before the first character of that substring and a space or punctuation mark after the last character, unless the substring is at the very beginning or end of the string (in this case there does not have to be a space in front or space or punctuation behind).
EXAMPLE 1: "120 brave students, 35 failed, remaining 85..." Numbers: 120, 35, 85
EXAMPLE 2: "2PAC and U2 have class" Numbers: // there aren't any numbers
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
int CharToInt(int c) {
return abs('0' - c);
}
int MakeNumber(std::vector < int > temp) {
int num;
if (temp.size() == 1)
num = temp[0];
if (temp.size() == 2)
num = temp[0] * 10 + temp[1];
if (temp.size() == 3)
num = temp[0] * 100 + temp[1] * 10 + temp[2];
if (temp.size() == 4)
num = temp[0] * 1000 + temp[1] * 100 + temp[2] * 10 + temp[3];
return num;
}
std::vector < int > ExtractNumbers(std::string str) {
std::vector < int > a;
bool found_number;
std::vector < int > temp;
for (int i = 0; i < str.length(); i++) {
// skip spaces
found_number = false;
while (str[i] == ' ' && i < str.length())
i++;
// inside word
while (str[i] != ' ' && i < str.length()) {
while (str[i] >= '0' && str[i] <= '9' && i < str.length()) {
temp.push_back(CharToInt(str[i]));
i++;
found_number = true;
}
i++;
}
if (found_number)
a.push_back(MakeNumber(temp));
temp.clear();
}
return a;
}
int main() {
std::vector < int > a = ExtractNumbers("120 brave students, 35 failed, remaining 85...");
std::vector < int > b = ExtractNumbers("2PAC and U2 have class");
for (int i: a) std::cout << i << " ";
std::cout << std::endl;
for (int i: b) std::cout << i << " ";
return 0;
}
OUTPUT:
120 35 85 // ✅
2 2 // ❌
Could you help me to modify this to work correctly for the example 2?
How could I check if there is space before and space/punctuation after the number is found?
| I found a way to solve this.
#include <iostream>
#include <string>
#include <vector>
std::vector < int > extract_numbers(std::string s) {
std::vector < int > vek;
for (int i = 0; i < s.length(); i++) {
std::string word;
while (s[i] == ' ' && i < s.length()) i++;
while (s[i] != ' ' && i < s.length()) word += s[i++];
int j = 0;
while (word[j] >= '0' && word[j] <= '9') j++;
std::string spaces = ".,;!?";
for (int i = 0; i < spaces.size(); i++)
if (word[j] == spaces[i] || word[j] == '\0') {
vek.push_back(std::stoi(word));
break;
}
}
return vek;
}
int main() {
std::string s;
std::getline(std::cin, s);
for (int i: extract_numbers(s))
std::cout << i << " ";
return 0;
}
|
72,021,541 | 72,021,608 | Using cin makes my code not work properly | I'm pretty new to c++ and tried this project and got it to work. Basically it takes a word and a sentence then changes the word to asterisks whenever said word is found in the sentence.
The problem I am facing is I tried taking it a step further by asking the user to input a word and input a sentence and then using those as a stored variable to run the code exactly the same way as before, but this doesn't work and only outputs the first word of the sentence. I can't figure it out why it's doing that. Everything is the same except for the cin. Am I just not understanding how cin works with strings?
Main code:
#include <iostream>
#include <string>
#include "functions.hpp"
using namespace std;
int main() {
string word = "brocolli";
string sentence = "Roll up that brocolli. I love brocolli!";
bleep(word, sentence);
for (int i = 0; i < sentence.size(); i++) {
cout << sentence[i];
}
cout << "\n";
return 0;
}
Header file:
#include <string>
void asterisk(std::string word, std::string &text, int i);
void bleep(std::string word, std::string &text);
Functions file:
#include <string>
#include "functions.hpp"
using namespace std;
void asterisk(string word, string &text, int i) {
for (int k = 0; k < word.size(); ++k) {
text[i+k] = '*';
}
}
void bleep(string word, string &text) {
for (int i = 0; i < text.size(); ++i) {
int match = 0;
for (int j = 0; j < word.size(); ++j) {
if (text[i+j] == word[j]) {
++match;
}
}
if (match == word.size()) {
asterisk(word, text, i);
}
}
}
Adjusted main code to include cin:
#include <iostream>
#include <string>
#include "functions.hpp"
using namespace std;
int main() {
string word;
string sentence;
cout << "Word: ";
cin >> word;
cout << "Sentence: ";
cin >> sentence;
bleep(word, sentence);
for (int i = 0; i < sentence.size(); i++) {
cout << sentence[i];
}
cout << "\n";
return 0;
}
| cout << "Sentence: ";
cin >> sentence;
The operator>> function you are using here stops reading at the first space character. It is not suitable for reading in a line of text.
|
72,022,183 | 72,022,261 | How do you restrict `resize()` from being called after constructing a vector? | I'm building a class that exposes a sequential container, with a fixed length, but the length isn't known at compile-time.
So when an instance of my class is constructed, a parameter is passed in, to indicate how big the vector needs to be.
But the length needs to be fixed after construction.
I need to guarantee that the resize() function cannot be invoked, while still allowing other parts of my code to modify individual elements within the vector.
(In other words, I can't simply expose the vector as vector<T> const&)
The same goes for any other function which modifies the length, such as insert(), push_back(), etc.
These functions need to be restricted or hidden.
Is this possible?
Or do I really need to build my own fixed_vector wrapper class to hide the undesired functions?
| Since C++20 you can return a std::span to the range in the vector. This allows access to the size and modifiable access to the elements, but not the vector's modifiers.
For example:
#include<vector>
#include<span>
class A {
std::vector<int> vec;
public:
/*...*/
auto getVec() {
return std::span(vec);
}
};
The return value can be used as a range, but there is no access to the container interface.
Depending on the types and initialization required, you may also be able to use an array std::unique_ptr instead of a std::vector if you know the size won't change. However that doesn't store the size, which you would then need to store yourself:
#include<vector>
#include<span>
class A {
std::size_t vec_size;
std::unique_ptr<int[]> vec;
public:
A(std::size_t size) : vec_size(size), vec(std::make_unique<int[]>(size)) { }
auto getVec() {
return std::span(vec, vec_size);
}
};
This may be slightly more space efficient since it doesn't require accounting for a difference in vector size and capacity.
|
72,022,362 | 72,022,392 | C++; Pass a std::array Random Access Iterator as a Function Parameter | So I've seen questions on here about how to pass through a std::vector::iterator as an argument parameter for a function, however, those solutions don't seem to apply when dealing with std::arrays. What I want to use this for is a Quick Sort function that takes in std::arrays. This is the code I have thus far:
#include <iostream>
#include <array>
#include <random>
#include <time.h>
using namespace std;
// Function declarations.
template<size_t SIZE>
void QuickSort(array<int, SIZE> arrayName, array<int, SIZE>::iterator low, \
array<int, SIZE>::iterator high);
template<size_t SIZE>
auto Partition(array<int, SIZE> arrayName, array<int, SIZE>::iterator low, \
array<int, SIZE>::iterator high);
// Main function.
int main()
{
// Set rand() seed to current time (NULL).
srand((unsigned)time(NULL));
// Declare array "randomNumberArray" of size #.
static array<int, 5> randomNumerArray = { 0 };
// Initialize array with random numbers.
for (auto it = randomNumerArray.begin(); it != randomNumerArray.end(); ++it)
*it = rand() % 500 + 1;
/*
This is where I would want to use the Quick Sort function to sort the array and
then print it out to the console.
*/
cin.get();
return 0;
}
// Function definitions. Standard Quick Sort syntax.
template<size_t SIZE>
void QuickSort(array<int, SIZE> arrayName, array<int, SIZE>::iterator low, \
array<int, SIZE>::iterator high)
{
if (low < high) {
// Function definition to be finished.
}
return;
}
/* Partition() returns auto to easily return the variable type I need
which is a Random Access Iterator.*/
template<size_t SIZE>
auto Partition(array<int, SIZE> arrayName, array<int, SIZE>::iterator low, \
array<int, SIZE>::iterator high)
{
auto pivot = high;
auto i = (low - 1);
for (auto j = low; j < pivot; ++j) {
if (*j < *pivot) {
int tempNum = 0;
tempNum = *(++i);
*i = *j;
*j = tempNum;
}
}
int tempNum = 0;
tempNum = *(++i);
*i = *pivot;
*pivot = tempNum;
return i;
}
As you can see, I've managed how to fit most of the pieces to this puzzle, I just don't know how to pass through low and high, which are meant to be of Random Access Iterator types, as argument parameters to the functions. Using std::array<type, size>::iterator doesn't work as it's not a type. I've also tried to add #include <iterator>, but to no avail.
EDIT: To clarify, it's not the value contained within the index that I'm trying to pass through, but the index itself which changes with each recursion.
| You need to use typename to hint to the compiler that iterator is a type
template<size_t SIZE>
void QuickSort(typename array<int, SIZE>::iterator low,
typename array<int, SIZE>::iterator high);
But that won't work either since SIZE is in a nondeduced context. It would be better to just make an iterator as a template
template<typename RandomIt>
void QuickSort(RandomIt low, RandomIt high);
|
72,023,700 | 72,034,755 | base64 encoding removing carriage return from dos header | I have been trying to encode the binary data of an application as base64 (specifically boosts base64), but I have run into an issue where the carriage return after the dos header is not being encoded correctly.
it should look like this:
This program cannot be run in DOS mode.[CR]
[CR][LF]
but instead its outputting like this:
This program cannot be run in DOS mode.[CR][LF]
it seems this first carriage return is being skipped, which then causes the DOS header to be invalid when attempting to run the program.
the code for the base64 algorithm I am using can be found at: https://www.boost.org/doc/libs/1_66_0/boost/beast/core/detail/base64.hpp
Thanks so much!
void load_file(const char* filename, char** file_out, size_t& size_out)
{
FILE* file;
fopen_s(&file, filename, "r");
if (!file)
return false;
fseek(file, 0, SEEK_END);
size = ftell(file);
rewind(file);
*out = new char[size];
fread(*out, size, 1, file);
fclose(file);
}
void some_func()
{
char* file_in;
size_t file_in_size;
load_file("filename.bin", &file_in, file_in_size);
auto encoded_size = base64::encoded_size(file_in_size);
auto file_encoded = new char[encoded_size];
memset(0, file_encoded, encoded_size);
base64::encode(file_encoded, file_in, file_in_size);
std::ofstream orig("orig.bin", std::ios_base::binary);
for (int i = 0; i < file_in_size; i++)
{
auto c = file_in[i];
orig << c; // DOS header contains a NULL as the 3rd char, don't allow it to be null terminated early, may cause ending nulls but does not affect binary files.
}
orig.close();
std::ofstream encoded("encoded.txt"); //pass this output through a base64 to file website.
encoded << file_encoded; // for loop not required, does not contain nulls (besides ending null) will contain trailing encoded nulls.
encoded.close();
auto decoded_size = base64::decoded_size(encoded_size);
auto file_decoded = new char[decoded_size];
memset(0, file_decoded, decoded_size); // again trailing nulls but it doesn't matter for binary file operation. just wasted disk space.
base64::decode(file_decoded, file_encoded, encoded_size);
std::ofstream decoded("decoded.bin", std::ios_base::binary);
for (int i = 0; i < decoded_size; i++)
{
auto c = file_decoded[i];
decoded << c;
}
decoded.close();
free(file_in);
free(file_encoded);
free(file_decoded);
}
The above code will show that the file reading does not remove the carriage return, while the encoding of the file into base64 does.
| Okay thanks for adding the code!
I tried it, and indeed there was "strangeness", even after I simplified the code (mostly to make it C++, instead of C).
So what do you do? You look at the documentation for the functions. That seems complicated since, after all, detail::base64 is, by definition, not part of public API, and "undocumented".
However, you can still read the comments at the functions involved, and they are pretty clear:
/** Encode a series of octets as a padded, base64 string.
The resulting string will not be null terminated.
@par Requires
The memory pointed to by `out` points to valid memory
of at least `encoded_size(len)` bytes.
@return The number of characters written to `out`. This
will exclude any null termination.
*/
std::size_t
encode(void* dest, void const* src, std::size_t len)
And
/** Decode a padded base64 string into a series of octets.
@par Requires
The memory pointed to by `out` points to valid memory
of at least `decoded_size(len)` bytes.
@return The number of octets written to `out`, and
the number of characters read from the input string,
expressed as a pair.
*/
std::pair<std::size_t, std::size_t>
decode(void* dest, char const* src, std::size_t len)
Conclusion: What Is Wrong?
Nothing about "dos headers" or "carriage returns". Perhaps maybe something about "rb" in fopen (what's the differences between r and rb in fopen), but why even use that:
template <typename Out> Out load_file(std::string const& filename, Out out) {
std::ifstream ifs(filename, std::ios::binary); // or "rb" on your fopen
ifs.exceptions(std::ios::failbit |
std::ios::badbit); // we prefer exceptions
return std::copy(std::istreambuf_iterator<char>(ifs), {}, out);
}
The real issue is: your code ignored all return values from encode/decode.
The encoded_size and decoded_size values are estimations that will give you enough space to store the result, but you have to correct it to the actual size after performing the encoding/decoding.
Here's my fixed and simplified example. Notice how the md5sums checkout:
Live On Coliru
#include <boost/beast/core/detail/base64.hpp>
#include <fstream>
#include <iostream>
#include <vector>
namespace base64 = boost::beast::detail::base64;
template <typename Out> Out load_file(std::string const& filename, Out out) {
std::ifstream ifs(filename, std::ios::binary); // or "rb" on your fopen
ifs.exceptions(std::ios::failbit |
std::ios::badbit); // we prefer exceptions
return std::copy(std::istreambuf_iterator<char>(ifs), {}, out);
}
int main() {
std::vector<char> input;
load_file("filename.bin", back_inserter(input));
// allocate "enough" space, using an upperbound prediction:
std::string encoded(base64::encoded_size(input.size()), '\0');
// encode returns the **actual** encoded_size:
auto encoded_size = base64::encode(encoded.data(), input.data(), input.size());
encoded.resize(encoded_size); // so adjust the size
std::ofstream("orig.bin", std::ios::binary)
.write(input.data(), input.size());
std::ofstream("encoded.txt") << encoded;
// allocate "enough" space, using an upperbound prediction:
std::vector<char> decoded(base64::decoded_size(encoded_size), 0);
auto [decoded_size, // decode returns the **actual** decoded_size
processed] // (as well as number of encoded bytes processed)
= base64::decode(decoded.data(), encoded.data(), encoded.size());
decoded.resize(decoded_size); // so adjust the size
std::ofstream("decoded.bin", std::ios::binary)
.write(decoded.data(), decoded.size());
}
Prints. When run on "itself" using
g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp -o filename.bin && ./filename.bin
md5sum filename.bin orig.bin decoded.bin
base64 -d < encoded.txt | md5sum
It prints
d4c96726eb621374fa1b7f0fa92025bf filename.bin
d4c96726eb621374fa1b7f0fa92025bf orig.bin
d4c96726eb621374fa1b7f0fa92025bf decoded.bin
d4c96726eb621374fa1b7f0fa92025bf -
|
72,023,780 | 72,024,397 | Are QML calls to C++ public slots executed in the c++ target thread, or in QML (main thread)? | Imagine we have a QObject-based c++ class called CppClass that is registered in the QML context with the name qmlCppClass and moved to a new thread using QObject::moveToThread("newThread* name").
Imagine CppClass has a public slot declared as void doSomething().
Imagine the root QML object/window has a signal defined inside it called signal().
Now assume 3 cases:
Inside my main.cpp (where I create the QML engine) I connect the signal() from QML to doSomething() in c++ in this way
QObject::connect("QObject* cast of my QML engine", SIGNAL(signal()), "CppClass* object name", SLOT(doSomething()));
Inside my QML code, I write this inside the onClicked() slot in a button qml type:
qmlCppClass.doSomething()
I use the Connections type in QML like this:
Connections {
target: qmlRoot
function onSignal() {
qmlCppClass.doSomething()
}
}
In each case, is the slot executed in the qml thread (a.k.a. main thread) or is it executed in the thread containing the CppClass object instance (a.k.a. target thread)?
| If connect is done with QueuedConnection then the slot will be executed on the receiver's thread, otherwise—on the sender's. Given you moved the receiver to another thread before making the connection, it would be a queued connection by default.
If there is no direct call to the connect function then invokeMethod might be used which has the same behavior as described above.
And if the direct call to a member function is used then it is executed in the thread where it is called from.
|
72,024,142 | 72,024,468 | Why does std::move cause SEGFAULT in this case? | Why does std::move() cause a SEGFAULT in this case?
#include <iostream>
struct Message {
std::string message;
};
Message * Message_Init(std::string message) {
Message * m = (Message*)calloc(1, sizeof(Message));
m->message = std::move(message);
return m;
}
int main() {
auto m = Message_Init("Hello");
return 0;
}
P.S. Please don't ask why Message is not constructed in a usual C++ manner.
| If you really want to do something like this, then you can use placement new. This allows you to construct an object in a chunk of memory that is already allocated.
Several of the standard containers use placement new to manage their internal buffers of objects.
However, it does add complications with the destructors of the objects you place. Read here for more info: What uses are there for "placement new"?
#include <iostream>
#include <memory>
struct Message {
std::string message;
};
Message * Message_Init(std::string message) {
void * buf = calloc(1, sizeof(Message));
Message * m = new (buf) Message(); // placement new
m->message = std::move(message);
return m;
}
int main() {
auto m = Message_Init("Hello");
m->~Message(); // Call the destructor explicitly
free(m); // Free the memory
return 0;
}
As @selbie suggested, I have added an explicit call to the destructor of Message, and also a call to free to deallocate the memory. I believe that the call to free should actually have pointed to the buffer originally returned by calloc since there could be a difference (so free(buf) in this case, but that pointer is not accessible here).
For example if you allocate a buffer for several objects, then calling free on the pointer to the second object would not be correct.
|
72,024,517 | 72,024,569 | What is atltime.h in MFC | Can someone will explain to me What is atltime.h ? I don't know how this header works. I tried to search it on google but i didn't get an answer of what atltime. h is.
| Not MFC, but ATL. ATL (Active Template Library) is a set of header files that ships with Visual Studio for making Windows programming easier without having to pull in all of MFC. These headers implement C++ class libraries that do useful things for legacy Windows programming.
It appear that atltime.h has the declarations for the following classes:
CTime, CTimeSpan, CFileTime, etc...
|
72,025,359 | 72,025,614 | fastest way of finding the end of a string | The question is simple: What is the quickest way of finding the position of the null-terminator ('\0') in a string buffer?
std::array<char, 100> str { "A sample string literal" };
I guess one option is to use the std::strlen.
Another option that I can think of is std::find or maybe even std::ranges::find:
const auto posOfNull { std::find( str.cbegin( ), str.cend( ), '\0' ) };
Now would it make a difference if an ExecutionPolicy (e.g. std::execution::par) was passed to it as its first argument? If it would, then which policy is the appropriate one for this particular case?
Or maybe a 3rd option that I don't know about?
|
What is the quickest way of finding the position of the null-terminator ('\0') in a string buffer?
I'm going to assume that you mean "to find the first null terminator".
Fastest depends on details. You have to measure to find out. std::strlen is a fairly safe default choice.
Now would it make a difference if an ExecutionPolicy (e.g. std::execution::par
The length of your buffer is 100. The overhead from multi threading may easily exceed the the time to find the terminator in a single thread.
If it would, then which policy is the appropriate one for this particular case?
The one that you have measured to be the fastest. None of them would break the correctness of the loop.
Or maybe a 3rd option that I don't know about?
You can use std::char_traits::length. Its benefits over std::strlen are that it works with all character types (compared to only char), and it is constexpr which allows using it in constant expressions.
|
72,025,770 | 72,100,387 | UWP Extended Foreground Session | So, I have made a few attempts to create an app in UWP, using C++/CX, and besides dreading the syntax, I had some fun.
I ran into troubles when I attempted to prevent the app from being suspended. Initially I tried using this resource, but I have learnt that there is a timeout. Then I tried getting rid of said timeout (though I cannot remember, nor find the exact resource for that).
Finally, I have found the holy grail, but it still wouldn't work.
auto ses = ref new ExtendedExecutionForegroundSession();
ses->Reason = ExtendedExecutionForegroundReason::Unconstrained;
ses->Description = "Michael";
auto res = create_task(ses->RequestExtensionAsync()).get();
if(res == ExtendedExecutionForegroundResult::Allowed)
{
ses->Revoked += ref new TypedEventHandler<Object^,ExtendedExecutionForegroundRevokedEventArgs^>(this, &App::OnRevoked);
MessageDialog^ messageDlg = ref new MessageDialog("Allowed to exec");
auto sh = create_task(messageDlg->ShowAsync());
sh.then([this](IUICommand^ comm) {});
Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
}
In this code snippet I am creating an unconstrained session extension, and, if I get permission, I will also display a message box, so I know that it worked.
Both in debug, and at runtime, I have no issues, and the laptop I am running this app on is mostly on battery. But the suspension event is still triggered, and no revoke event is ever called.
I'll provide here both code snippets:
void App::OnRevoked(Object^ sender, ExtendedExecutionForegroundRevokedEventArgs^ e)
{
MessageDialog^ messageDlg = ref new MessageDialog(e->Reason.ToString());
auto sh = create_task(messageDlg->ShowAsync());
sh.then([this](IUICommand^ comm) {});
}
void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
{
MessageDialog^ messageDlg = ref new MessageDialog("Suspension event raised");
auto sh = create_task(messageDlg->ShowAsync());
sh.then([this](IUICommand^ comm) {});
}
My quest, as many others' before, is to find the workaround that will prevent this behaviour, and so my question resumes to this:
How do I prevent an UWP from being suspended, without any regard to the hardware it's running on ( it will run on a PC, be it desktop or laptop), and without a time or resource constraint?
| I solved the issue, I ended up creating a new project from scratch in c#, and recreating the entire project (luckily I didn't have much trouble, since there wasn't too much to implement). In the end, it might have been something to do with either my xaml or some wrong API call.
Thank you Roy Li - MSFT for your time.
|
72,025,874 | 72,028,029 | Proper use of std::reference_wrapper in union | Can someone please explain what is wrong with this pattern? When I try to compile it I get errors for each type of the following type.
error: no match for 'operator=' (operand types are 'std::reference_wrapperstd::__cxx11::basic_string<char>' and 'int')
string_reference = property;
struct PropertyPointer {
int type;
std::string name;
union {
std::reference_wrapper<int*> int_reference;
std::reference_wrapper<double*> double_reference;
std::reference_wrapper<float*> float_reference;
std::reference_wrapper<std::string*> string_reference;
};
PropertyPointer(std::string name, auto&& property): name{name} {
if(std::is_same<decltype(property), int*>::value) {
type = 'i';
int_reference = property;
}
else if(std::is_same<decltype(property), double*>::value) {
type = 'd';
double_reference = property;
}
else if(std::is_same<decltype(property), float*>::value) {
type = 'f';
float_reference = property;
}
else if(std::is_same<decltype(property), std::string*>::value) {
type = 's';
string_reference = property;
}
}
};
| Answer of your question
if statements are not marked constexpr
The reason why your code does not compile is because, even if the if statements will be evaluated to false at compile time, the branches contained by those if statements will be compiled.
In your example, you can mark those if statements as constexpr to compile the code.
However, it will (probably) not work as you intend it to, because the type of property will be an rvalue of the pointer you passed to the constructor.
Here is an example of how I made it work (if I understood correctly what you were trying to do:
struct PropertyPointer {
int type;
std::string name;
union {
std::reference_wrapper<int*> int_reference;
std::reference_wrapper<double*> double_reference;
std::reference_wrapper<float*> float_reference;
std::reference_wrapper<std::string*> string_reference;
};
PropertyPointer(std::string name, auto&& property): name{name} {
using Type = ::std::remove_cvref_t<decltype(property)>;
if constexpr (std::is_same<Type, int*>::value) {
type = 'i';
int_reference = property;
} else if constexpr (std::is_same<Type, double*>::value) {
type = 'd';
double_reference = property;
} else if constexpr (std::is_same<Type, float*>::value) {
type = 'f';
float_reference = property;
} else if constexpr (std::is_same<Type, std::string*>::value) {
type = 's';
string_reference = property;
}
}
};
std::variant
It seems to me that you are not familiar with std::variant.
The class template std::variant represents a type-safe union.
source
Its job is to replace unions (that is a C feature) with type safe classes with extra functionalities.
Here is a quick example of how I would have done it:
class PropertyPointer {
public:
PropertyPointer(
auto&& property
)
: m_value{ &property }
{
// compare types if you want it to compile but have the object empty
}
template <
typename T
> [[ nodiscard ]] bool hasType() // true if the types matches the one inside (pointer or not)
{
using Type = ::std::remove_cvref_t<::std::remove_pointer_t<::std::remove_cvref_t<T>>>;
return std::holds_alternative<Type*>(m_value);
}
private:
::std::variant<int*, float*, double*, ::std::string*> m_value;
};
int main()
{
PropertyPointer property{ ::std::string{ "yes" } };
property.hasType<int>(); // false
property.hasType<float>(); // false
property.hasType<double>(); // false
property.hasType<::std::string>(); // true
property.hasType<const ::std::string>(); // true
property.hasType<::std::string&>(); // true
property.hasType<const ::std::string*>(); // true
property.hasType<const ::std::string *const>(); // true
}
This example is here to show you that you can add some extra features like comparing with and without the pointer for the same behavior.
This example isn't here to tell you that "it is how it has to be done" but rather an example of how modern c++ features can make your life easier.
|
72,026,112 | 72,026,180 | Capture shared_ptr in lambda | I want to capture a shared_ptr in my lambda expression. Tried two methods:
Capture the shared pointer
error: invalid use of non-static data member A::ptr
Create a weak pointer and capture it (Found this via some results online). I'm not sure if I'm doing it the right way
error: ‘const class std::weak_ptr’ has no member named ‘someFunction’
Before anyone flags it as a duplicate, I am aware it might be similar to a some other questions but none of their solutions seem to work for me. Want to know what I'm doing wrong and how to resolve it, that's why I'm here.
file.h
#include "file2.h"
class A{
private:
uint doSomething();
std::shared_ptr<file2> ptr;
}
file.cpp
#include "file.h"
uint A::doSomething(){
...
// Tried using weak pointer
//std::weak_ptr<Z> Ptr = std::make_shared<Z>();
auto t1 = [ptr](){
auto value = ptr->someFunction;}
// auto t1 = [Ptr](){
// auto value = Ptr.someFunction;}
...
}
| You cannot capture member directly, either you capture this or capture with an initializer (C++14)
auto t1 = [this](){ auto value = ptr->someFunction();};
auto t1 = [ptr=/*this->*/ptr](){ auto value = ptr->someFunction();};
|
72,026,830 | 72,028,789 | Zip directory recursion | I am working on creating zip archive using old Qt - ZipWriter class. The problem is when I want to add the directory. The default Qt code for addDirectory method - d->addEntry(ZipWriterPrivate::Directory, archDirName, QByteArray());. It does not add any content, only the empty directory. So, I have improved it to add the directories and content as well.
My code:
QList<QString> dirs;
int recursion = 0;
void ZipWriter::addDirectory(const QString &dirPath)
{
QDir archDir(dirPath);
archDir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
dirs << addDirSeparator(archDir.dirName());
if (archDir.exists()) {
QString archDirName = "";
if (recursion > 0) {
for (int i = recursion; i < dirs.count(); i++) {
archDirName = dirs.first().append(dirs.at(i));
}
} else {
archDirName = dirs.at(recursion);
}
if (!archDir.isEmpty()) {
const QStringList archFileList = archDir.entryList();
if (archFileList.count() > 0) {
for (QString archFile : archFileList) {
QFileInfo archFileInfo(QDir::toNativeSeparators(QString("%1/%2").arg(archDir.absolutePath(), archFile)));
if (archFileInfo.isDir()) {
recursion++;
addDirectory(archFileInfo.absoluteFilePath());
} else {
QFile zipFile(archFileInfo.absoluteFilePath());
zipFile.open(QIODevice::ReadOnly);
addFile(QString("%1%2").arg(archDirName, archFile), zipFile.readAll());
zipFile.close();
}
}
}
} else {
d->addEntry(ZipWriterPrivate::Directory, archDirName, QByteArray());
}
}
}
Now, it adds the directory and content recursively but it has issue when directory is on the same level, it appends it to the end. I think, I must use the STL container to keep track of the directory for example QMap but the question is how to get the current directory level? Any ideas? Thank you.
Updated: 01.05.2022
I have change my code to this:
void ZipWriter::addDirectory(const QString &dirPath)
{
QDirIterator dirIt(dirPath, QDir::AllEntries | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
while (dirIt.hasNext()) {
QString archDirPath = dirIt.next();
QFile zipFile(archDirPath);
zipFile.open(QIODevice::ReadOnly);
if (!dirIt.fileInfo().isDir()) {
addFile(archDirPath, zipFile.readAll());
}
zipFile.close();
}
}
It adds everything recursively and in correct order but I have another issue. Now, it adds the full path to the archive. For example, I want to add this folder and it's content to the archive: 22610.1_amd64_en-us_professional_00fb7ba0_convert.
In the archive I get: C:\Users\userProfile\Downloads\22610.1_amd64_en-us_professional_00fb7ba0_convert. Any ideas how to make this relative path or trim it? Thank you.
| You can use QDirIterator to recursively iterate over directory and subdirectories, and I believe you dont need to add nonempty directories at all, just files will be fine.
And why would you use stl container in qt, please use qt containers.
|
72,027,058 | 72,027,807 | Is it possible to expand a macro into two piece of data with different types | UPDATE
It seems that the original question is not that clear, so I made another example to specify what I need.
#define RPC_FUNC(X) &X,??? // I don't know how...
class Test {
public:
static void func(int a) {}
};
int main()
{
const auto ptr1 = std::make_pair(&Test::func, "Test::func");
// const auto ptr2 = std::make_pair(RPC_FUNC(Test::func));
// ptr2.first(123); // this should call the function Test::func
// std::cout << ptr2.second; // this should print the string "Test::func"
return 0;
}
How to define the macro RPC_FUNC to make this code work? Meaning that I want to make ptr1 and ptr2 exactly the same.
ORIGINAL
I want to do a piece of code like this:
template<typename F> // F is the type of some functions
void func(F f, const std::string& funcMark) {
// do something
}
I want to pass a non-static member function and a string into the function func.
Sometimes, the second parameter is just the name of the first one. Let's see an example:
namespace sp {
class Test {
public:
void doJob() {}
};
}
func(&sp::Test::doJob, "doJob");
What I'm trying to do is to do the call above like this: func(MY_MARCO(sp::Test::doJob)).
Meaning that, the macro MY_MACRO should do expand its parameter sp::Test::doJob into &sp::Test::doJob, "doJob".
| The specification what the macro should precisely do is dim. The stringizing operator # can turn macro argument into string literal:
// example code what it does
#include <iostream>
#define YOUR_MACRO(X) X() << " from " << #X "()"
int foo() { return 42; }
int main() { std::cout << YOUR_MACRO(foo) << std::endl; }
That outputs
42 from foo()
Turning string literal into std::string is also trivial:
#include <iostream>
#include <string>
#define YOUR_MACRO(X) X() << " from " << std::string(#X "()")
int foo() { return 42; }
int main() { std::cout << YOUR_MACRO(foo) << std::endl; }
Works same. So where are you stuck?
UPDATE:
Specification is now lot better! But ... it
is basically same what I already posted that you should use stringizing operator # in macro:
#include <iostream>
#define RPC_FUNC(X) &X, #X
class Test {
public:
static void func(int a) {
std::cout << "called Test::func(" << a << ")" << std::endl;
}
};
int main() {
const auto ptr1 = std::make_pair(&Test::func, "Test::func"); // gets warning about unused variable
const auto ptr2 = std::make_pair(RPC_FUNC(Test::func));
ptr2.first(123); // prints "called Test::func(123)"
std::cout << ptr2.second << std::endl; // prints "Test::func"
return 0;
}
|
72,027,359 | 72,027,509 | How to input to vector correctly in C++ | When I try to input to vector by following code, I get a segmentation fault as shown below.
I defined the vector and set N, and tried to input a vector with N elements.
What is the root cause of this?
#include <iostream>
#include <vector>
using namespace std;
int N;
vector<int> A(N);
int main(){
cin>>N;
for(int i=0;i<N;i++) cin>>A[i];
}
[ec2-user@ip-10-0-1-187 ]$ ./vector_input
1
1
Segmentation fault
| That's because constructor of A is called with N=0. When you input N, it doesn't affect the vector at all. If you really want to keep using globals, then use std::vector::resize but the recommended way would be:
int main(){
std::size_t n;
std::cin >> n;
std::vector<int> A(n);
for(auto & x : A) std::cin >> x;
}
|
72,027,373 | 72,027,501 | How to get a removed-reference tuple type without using an instance in C++ | I wrote a test framework for testing function output (see code below).
template <class FuncTy, class... IndexType>
typename std::enable_if<std::tuple_size<typename function_helper<FuncTy>::arguments>::value == sizeof...(IndexType)
and std::is_same_v<typename function_helper<FuncTy>::return_type, AnswerTy>
and not is_member_function_pointer_v<FuncTy>, void>::type
test(FuncTy func, IndexType... arg_indexes) {
using function_args_tuple = typename function_helper<FuncTy>::arguments;
using function_return_type = typename function_helper<FuncTy>::return_type;
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
function_args_tuple params; /// error is here
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/// .....
}
It works well for functions that do not have references in arguments.
e.g.:
for fucntion int f(int x, vector<int> y); (i.e., no references in argument list), the type of params is a std::tuple<int, vector<int>>, so the params can instantiate normally with code above,
but for functions like int f(int& x, vector<int>& y); (i.e., one or more references in argument list), the type of params becomes std::tuple<int&, vector<int>&>, which is not able to instantiate with code above.
The type of the tuple params is affected by argument list of a function (done with another function), the type of the tuple is undefined, so I just cannot do like this and this, since both of the solutions in the two links use a make_tuple explictly and an instantiated tuple object.
So my question is how to remove the references without instantiate the tuple. (e.g., make tuple<int&, vector<int>&> to tuple<int, vector<int>>).
Or else if there is some ways to instantiate a tuple with references in the tuple's template argument list without hard-coded make_tuple calls.
| You can get the element type of the tuple through template partial specialization and apply std::decay to those types to remove references, something like this
#include <type_traits>
#include <tuple>
template<class Tuple>
struct decay_args_tuple;
template<class... Args>
struct decay_args_tuple<std::tuple<Args...>> {
using type = std::tuple<std::decay_t<Args>...>;
};
Then you can get a tuple of the decay argument types through the helper class
decay_args_tuple<decltype(function_args_tuple)>::type params;
Note that the argument type is still required to be default constructible.
|
72,027,739 | 72,074,304 | Is Q_INTERFACES macro needed for child classes? | If I have class A that implements an interface (and uses Q_INTERFACES macro), then does child class B : public A also need to use the Q_INTERFACES macro?
For example:
IMovable.h
#include <QObject>
class IMovable
{
public slots:
virtual void moveLeft(int distance) = 0;
virtual void moveRight(int distance) = 0;
virtual void moveUp(int distance) = 0;
virtual void moveDown(int distance) = 0;
signals:
virtual void moved(int x, int y) = 0;
};
Q_DECLARE_INTERFACE(IMovable, "my_IMovable")
A.h
#include <QObject>
#include "IMovable.h"
class A : public QObject, public IMovable
{
Q_OBJECT
Q_INTERFACES(IMovable)
public:
explicit A(QObject *parent = nullptr);
virtual ~A();
public slots:
//implement IMovable public slots
void moveLeft(int distance) override;
void moveRight(int distance) override;
void moveUp(int distance) override;
void moveDown(int distance) override;
signals:
//implement IMovable signals
void moved(int x, int y) override;
};
B.h
#include "A.h"
class B : public A
{
Q_OBJECT
// Do I need Q_INTERFACES(IMovable) here?
...
};
| Q_INTERFACES is needed for the qobject_cast function to work correctly with the interfaces a class implements. So if you want to use this function you have to place Q_INTERFACES into your class.
Docs aren't clear on what happens with the inheritance but the implementation of the generated qt_metacast function is always calling their parent qt_metacast. So in your example, even if you don't put the Q_INTERFACES macro into the B class it should still work with the qobject_cast function because it would pass it to A to execute.
|
72,027,843 | 72,074,356 | How does os figure if a dll is already loaded in memory or how does os figure two dll are the same? | In my comprehension, "dll/so" can be shared between programs(processes). for example when "libprint.so" is loaded in "main"(called main1) at first time, "libprint.so" is loaded from disk into memory, if we start another "main"(called main2), "libprint.so" will not loaded from disk but mapped from memory because "libprint.so" has been already loaded in memory once.
So i design an experiment:
main.cc --> main
#include <iostream>
#include <chrono>
#include <thread>
void printinfo();
int main() {
printinfo();
while(true) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
return 0;
}
print1.cc --> libprint1.so
#include <iostream>
void printinfo() {
std::cout << "Print One" << std::endl;
}
print2.cc --> libprint2.so
#include <iostream>
void printinfo() {
std::cout << "Print Two" << std::endl;
}
mv libprint1.so libprint.so
./main
// output is: Print One
keep the main.exe running, and replace the libprint.dll with libprint2.dll, like
mv libprint2.so libprint.so
./main
// output is: Print Two
why the output is "Print Two"? I expect it to be "Print One" the "libprint.so" is already loaded in memory, although i changed the content of "libprint.so", but the so's absolute path is the same as before, how does the operating system know the "new libprint.so" is different with before?
Thanks for @Michael Chourdakis, in windows environment, the libprint.dll could not be replaced when main.exe is running.
But the problem is still there in linux(libprint.so could be replaced in
linux), @user253751 says there must be some tricks that linux figure different "so", i want to know exactly what the tricks are, do i have to read the linux os source code ?
|
i want to know exactly what the tricks are, do i have to read the linux os source code ?
What actually happens when you run main (which is presumably linked against libprint.so) (or at least "explainlikeimfive" version):
At the time the static link is performed (g++ main.cpp ./libprint.so or similar), the static linker records that (a) your program is dynamically linked and (b) that it requires ./libprint.so to run. You can see this by looking at the output from readelf -d main. Another thing that is recorded is the dynamic loader (aka ELF interpreter), which you can see with readelf -l main.
When the Linux kernel starts the new process to run main in, it discovers (by reading program headers) which ELF interpreter is to be used, mmaps that interpreter into memory, and transfers control to it. It is the job of the interpreter to mmap other libraries (including libprint.so), relocate them, arrange for proper symbol resolution, etc. etc.
The ELF interpreter uses open and mmap system calls to actually bring libprint.so into the process (this happens long before main() is called.
When any process calls open("/some/path", ...), the OS (the Linux kernel) performs directory lookups to map the given path to a particular mounted filesystem and a unique inode on that that filesystem. Finally it (the OS) checks to see if that inode has already been opened by any other currently running process. If the file is open, then the kernel can reuse some of the in-kernel-memory structures it already allocated for that file <-- this is where the kernel discovers that it may not have to allocate new memory pages for libprint.so but can re-use the ones it already has.
When you do mv libprint2.so libprint.so, you change the inode number of libprint.so, so the kernel knows it's a totally different file. You can observe this by using ls -li libprint.so before and after mv.
|
72,027,928 | 72,028,003 | Min and Max function return gibberish value when array is not full | I need to create a program that collects user input until the user presses 0 or has inputted 10 values. Then I need to create a function, without using built-in to get the minimum and maximum values. However, when 9 or less values are inputted, the minimum and maximum function return a random value. Here is my code:
#include <iostream>
using namespace std;
int getMin(int array[], int n);
int getMax(int array[], int n);
int main()
{
int array[10];
cout << "This program will ask the user to input various numbers (positive or negative but not zero) and perform basic statistics on these numbers.\n";
for(int i=0; i<10; i++){
cout<<"\nInput an integer: ";
cin>>array[i];
if(array[i]==0) {
break;
}
}
int n = sizeof(array) / sizeof(array[0]);
cout << "Minimum element of array: " << getMin(array,n) << "\n";
cout << "Maximum element of array: " << getMax(array,n);
return 0;
}
int getMin(int array[], int n)
{
int minimum = array[0];
for (int i = 1; i < n; i++)
if (minimum > array[i]) {
minimum=array[I];
}
return minimum;
}
int getMax(int array[], int n)
{
int maximum = array[0];
for (int i = 1; i < n; i++)
if (maximum < array[i]) {
maximum=array[I];
}
return maximum;
}
How do I make it so even if I input less than 10 values, it returns the correct minimum and maximum value?
| You are breaking the loop on less than 10 values, if need be, but still iterate over the entire array. Instead you should only iterate over those values that actually have been written to, reading the others results in undefined behaviour as the array is not initialised at these locations (and thus contains the 'giberish' you see...).
So:
size_t n;
for(n = 0; n < sizeof(array)/sizeof(*array); ++n)
{
// use n instead of i
}
getMin(array, n);
getMax(array, n);
|
72,027,998 | 72,028,800 | Polygon collision (sometimes) not working, possibly float error | I am writing a program in C++ using OpenGL to draw elements. This is a simple 2D game, in which a square is supposed to change its direction once it hits one of the walls, i.e. the bounds of the screen. To set up the bounding box, I have made tiny squares spanning the length of the sides. My coordinate system is from -1 to 1 in all directions.
Sometimes it all works, but eventually the moving square will go outside the window. It seems my program recognizes the collision, but still nothing stops it from moving past the bounds. Here is my check for collision:
bool checkCollisionRectRect(Rectangle* p1, Rectangle* p2) {
float eps = 0.005;
RectHitbox* rect1 = (RectHitbox*)p1->getHitbox();
RectHitbox* rect2 = (RectHitbox*)p2->getHitbox();
if (rect1->x < rect2->x + rect2->w + eps &&
rect1->x + rect1->w + eps > rect2->x &&
rect1->y < rect2->y + rect2->h + eps &&
rect1->h + rect1->y + eps > rect2->y) {
return true;
}
return false;
}
This is how collisions are checked for, for the time being for every single frame:
void Game::handleBallWallCollision() {
bool collisionX = checkCollision(this->ball, this->boundBoxes->at(0)) ||
checkCollision(this->ball, this->boundBoxes->at(1));
bool collisionY = checkCollision(this->ball, this->boundBoxes->at(2)) ||
checkCollision(this->ball, this->boundBoxes->at(3));
if (collisionX) { // Collision X
ball->flipDirectionX();
} else if (collisionY) { // Collision Y
ball->flipDirectionY();
}
}
In order to avoid floating point errors, I have added the eps value. Still I have no idea what is wrong, and why the square sometimes jumps past the bounds. Has anyone encountered this problem before, and possibly solved it by some clever means?
| You don't need an epsilon. In fact, it is the source of the error.
if (collisionX) { // Collision X
ball->flipDirectionX();
When the ball gets to move slow enough, once it enters the area of epsilon, it will just bounce left and right every frame.
But just removing the epsilon will not be enough to fix the issue. What you need is:
if (collisionXLeftSide) { // Collision X on the left
ball->goRight();
You need to be explicit. If the collision is on the left side, you need to force the ball to go right, and vice versa. That way, due to floating point errors, if you measure two collisions for the same wall, your ball still bounce to the correct side.
|
72,028,410 | 72,033,911 | OpenMP has low CPU usage | My OpenMP Implementation shows a really bad performance. When I profile it with vtune, I have a super low CPU usage and I don't know why. Does anyone have an idea?
Hardware:
NUMA architecture with 28 cores (56 Threads)
Implementation:
struct Lineitem {
int64_t l_quantity;
int64_t l_extendedprice;
float l_discount;
unsigned int l_shipdate;
};
Lineitem* array = (Lineitem*)malloc(sizeof(Lineitem) * array_length);
// array will be filled
#pragma omp parallel for num_threads(48) shared(array, array_length, date1, date2) reduction(+: sum)
for (unsigned long i = 0; i < array_length; i++)
{
if (array[i].l_shipdate >= date1 && array[i].l_shipdate < date2 &&
array[i].l_discount >= 0.08f && array[i].l_discount <= 0.1f &&
array[i].l_quantity < 24)
{
sum += (array[i].l_extendedprice * array[i].l_discount);
}
}
Additionally as information, I am using cmake and clang.
| I was able to find the cause of my poor OpenMP performance. I am running my OpenMP code inside a thread pinned to a core. If I don't pin the thread to a core, then the OpenMP code is fast.
Probably the threads created by OpenMP in the pinned thread are also executed on the core where the pinned thread is pinned. Consequently, the whole OpenMP code runs on only one core with many threads.
|
72,029,266 | 72,029,649 | Deleting minimum node from BST results in segmentation fault C++ | I am trying to delete the minimum node from a BST. But I get a seg fault.
To my understanding, minimum node will have no children, hence deleting it would not result in desserted leftover subtree. I am unsure on how to remove a node from a BST, I saw some solution that uses free() instead of delete. Where did I go wrong?
Source code for testing:
https://onlinegdb.com/kiOZQee3w
Codes are in bst.hpp
Constructor starts at line 23
insert function
starts at line 96
delete_min function starts at line 142
min
function starts at line 180 to 203
***Added some code in editing
void delete_min()
{
Node* min_node = min();
Node* min_parent = min_node->parent; //Added this
if(!root)
{
return;
}
// If min is root (Added this)
if(!root->left)
{
auto tmp = root;
root = root->right;
delete tmp;
return;
}
min_parent->left = min_node->right; //Added this
delete min_node;
--size;
}
Node* min()
{
if(root == nullptr)
{
return root;
}
else
{
return min(root);
}
}
Node* min(Node* node)
{
while(node->left != nullptr)
{
node = node->left;
}
return node;
}
| At very first your assumption that the minimum node doesn't have children is wrong; it doesn't have a left child, but it might have a right child; consider the most simple case of the root node and one single child that's greater than:
1
\
2
Then for removing a node you cannot just only delete it, but you need to adjust it's parent's left pointer, too – or the root pointer, if the root is the minimum node. You can simply set it to the minimum's right child (can either of another node or a null pointer).
Update according to the code code provided on online GDB (this version is not matching the version in the question!):
Node* min_node = min();
if(min_node->right != nullptr)
{
min_node->parent->left = min_node->right;
}
delete min_node;
You need to update the parent's left child unconditionally – if there's no grandchild, you'll just copy the null pointer that way, which is fine, as there won't be a right child any more anyway (the only one gets deleted).
But if there's a grandchild you need to update its parent (which otherwise would remain pointing to the deleted node, thus get dangling!):
Node* min_node = min();
min_node->parent->left = min_node->right;
if(min_node->right)
{
min_node->right->parent = min_node->parent;
}
delete min_node;
For this, though, you need the parent node available, too, thus you need to adjust the lookup of the minimum appropriately unless your nodes contain a link to their respective parent, too. Assuming this not being the case then your iteration might look as follows:
void deleteMin()
{
// special handling: empty tree
if(!root)
{
return;
}
// special handling: minimum is root
if(!root->left)
{
auto tmp = root;
root = root->right;
delete tmp;
return;
}
// now look for the minimum as you had already, but keep
// track of the parent node as well!
auto parent = root;
child = root->left;
while(child->left)
{
parent = child;
child = child->left;
}
// OK, minimum found; essential step: adjust its parent!
parent->left = child->right; // works for both a child available or not
// now can safely delete:
delete child;
}
|
72,029,420 | 72,029,497 | Char array to string and copy character \0 | How can I convert a char field to a string if I have the '\ 0' character stored in some position. For example, if I have "ab \ 0bb", the a.lenght () command will show me that I have only two characters stored
string getString(char *str, int len)
{
str[len] = '\0';
string strBuffer = string(str);
cout << strBuffer.length() << endl;
return strBuffer;
}
| As mentioned in the comments, std::string (which I will assume string and the question is referring to) has a constructor taking the length and allowing null characters:
string getString(char *str, int len)
{
return {str, len};
}
or if you want to be explicit (to avoid confusion with an initializer list constructor)
string getString(char *str, int len)
{
return string(str, len);
}
The str parameter should probably also have type const char*, not char*, and the type of len should probably be std::size_t. And probably string should be qualified as std::string as well instead of using using namespace std; or using std::string; (depends on context).
|
72,030,811 | 72,030,986 | cppcheck: member variable not initialized in the constructor | The following code, as far as I can tell, correctly initializes the variables of the derived class B:
#include <utility>
struct A {
int i;
};
struct B : A {
int j;
explicit B(A&& a) : A(std::move(a)), j{i} { }
};
int main()
{
A a{3};
B b(std::move(a));
return 0;
}
Running cppcheck with --enable=all gives the warning:
[test.cpp:9]: (warning) Member variable 'A::i' is not initialized in
the constructor. Maybe it should be initialized directly in the class
A?
Is there a reason for this (false, I think) warning?
| Yes, this looks like a false positive. Base class subobjects are initialized before direct member subobjects and A(std::move(a)) will use the implicit move constructor which initializes this->i with a.i, so this->i will be initialized before the initialization of this->j is performed (which reads this->i).
The argument given to the constructor in main is also completely initialized via aggregate initialization, so a.i's value will not be indeterminate either.
|
72,030,923 | 72,031,262 | How to convert a windows FILETIME to a std::chrono::time_point<std::chrono::file_clock> in C++ | I'm looking for a way to convert a Windows FILETIME structure to a std::chrono::time_point< std::chrono::file_clock> so that I can build a difference between two file times and express that duration f.e. in std::chrono::microseconds.
EDIT: Here is a complete godbolt example of Howard's Answer.
| Disclaimer: I don't have a Windows system to test on.
I believe that one just needs to take the high and low words of the FILETIME and interpret that 64 bit integral value as the number of tenths of a microsecond since the std::chrono::file_clock epoch:
FILETIME ft = ...
file_clock::duration d{(static_cast<int64_t>(ft.dwHighDateTime) << 32)
| ft.dwLowDateTime};
file_clock::time_point tp{d};
Both the units and the epoch of FILETIME and file_clock (on Windows) are identical.
|
72,030,976 | 72,031,446 | Basic forward list using unique_ptrs | As an exercise in learning C++, I want to build my own forward list using raw pointers and using unique_ptrs. Using raw pointers, I have:
struct node_raw {
node_raw(int data_, node_raw *next_) : data(data_), next(next_) {}
int data;
node_raw *next;
};
Then I can write this
int main() {
node_raw r1{1, nullptr};
node_raw r2{2, &r1};
node_raw r3{3, &r2};
}
to get a forward list: r3 -> r2 -> r1.
Now I want to do the same using unique_ptrs.
struct node_unique {
node_unique(int data_, std::unique_ptr<node_unique> next_)
: data(data_), next(std::move(next_)) {}
int data;
std::unique_ptr<node_unique> next;
};
This is what I have so far for client code:
int main() {
node_unique u1{1, nullptr};
node_unique u2{2, std::make_unique<node_unique>(std::move(u1))};
node_unique u3{3, std::make_unique<node_unique>(std::move(u2))};
}
This gives u3.next->data = 2, so it seems to work. But is it right? Why do I need std::move twice to make a new node? Is it now invalid to query u1.data because it has been moved from? Basically, what is the canonical way to implement a minimal forward list using unique_ptrs?
|
Why do I need std::move twice to make a new node?
You cannot copy node_unique because it has implicitly deleted copy constructor because of std::unique_ptr member.
Is it now invalid to query u1.data because it has been moved from?
No. The implicitly generated move constructor will copy the member. It's not invalid to read the int member that was copied from.
But is it right?
There isn't a huge problem1 with the node class itself, but the way that you're using it may potentially be misleading. u1 and u2 aren't part of the list whose root is u3. The list nodes are shallow copies of the moved-from u1 and u2.
You don't necessarily need the variables; since the list elements will be dynamic, you can create them directly:
node_unique root (
3,
std::make_unique<node_unique>(
2,
std::make_unique<node_unique>(
1,
nullptr
)
)
);
Basically, what is the canonical way to implement a minimal forward list using unique_ptrs?
"Minimal" is relative to what your requirements are. You could make it more minimal by removing the constructor to make the node an aggregate.
I wouldn't say that there is a "canonical" way to implement a forward list, but it would be expected to meet the concept of a Container. That would however be less minimal.
1 Except for the fact that destructor has linear recursion depth which will cause stack overflow with moderately sized lists as pointed out by Remy Lebeau.
You should implement a custom destructor that destroys the nodes iteratively. This requires a bit of thought to prevent the smart pointer destructors from delving into recursion.
|
72,031,008 | 72,031,423 | How can I sort a 2D vector in C++ by the first and second index? | I was wondering how in C++ I could sort a 2D vector so that it is sorted by both elements. It would be sorted in ascending order by the first element, and if there are multiple of the first element, they will be sorted by ascending order of the second element. Here is an example of what I mean:
vector<vector<int>> vec = {{10, 23}, {10, 22}, {1, 100}, {13, 12}};
this would get sorted into:
{{1, 100}, {10, 22}, {10, 23}, {13, 12}}
| If you are using C++20 std::ranges::sort would be a good option:
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<std::vector<int>> vec = {{10, 25}, {10, 23}, {10, 22},
{10, 24}, {1, 100}, {13, 12}};
std::ranges::sort(vec);
for (const auto& row : vec)
for (const auto& col : row)
std::cout << col << " ";
}
Live sample
Output:
1 100 10 22 10 23 10 24 10 25 13 12
If not std::sort works just as well:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> vec = {{10, 25}, {10, 22}, {10, 26},
{10, 24}, {1, 100}, {13, 12}};
std::sort(vec.begin(), vec.end());
for (const auto& row : vec)
for (const auto& col : row)
std::cout << col << " ";
}
Live sample
Output:
1 100 10 22 10 24 10 25 10 26 13 12
|
72,031,323 | 72,087,315 | How to generate a symmetric key in C or C++ the same way this script does? | I am implementing Azure DPS (device provisioning service) for my ESP32-based firmware.
The bash script I use so far is as follows (where KEY is the primary key of the DPS enrolment group and REG_ID is the registration device Id for the given ESP it runs on):
#!/bin/sh
KEY=KKKKKKKKK
REG_ID=RRRRRRRRRRR
keybytes=$(echo $KEY | base64 --decode | xxd -p -u -c 1000)
echo -n $REG_ID | openssl sha256 -mac HMAC -macopt hexkey:$keybytes -binary | base64
I use the Arduino platform in platformIO.
How to translate the script in C/C++?
[UPDATE] The reason why I can't run openSSL: I need to generate the symmetric key from the actual device MAC address in order to obtain the credential from DPS and then be granted to connect to IoT Hub - I run on an EPS32-based custom PCB. No shell. No OS.
| I manage to do it by using bed library (which is available from both ESP32/Arduino platforms).
Here is my implementation for the Arduino platform:
#include <mbedtls/md.h> // mbed tls lib used to sign SHA-256
#include <base64.hpp> // Densaugeo Base64 version 1.2.0 or 1.2.1
/// Returns the SHA-256 signature of [dataToSign] with the key [enrollmentPrimaryKey]
/// params[in]: dataToSign The data to sign (for our purpose, it is the registration ID (or the device ID if it is different)
/// params[in]: enrollmentPrimaryKey The group enrollment primary key.
/// returns The SHA-256 base-64 signature to present to DPS.
/// Note: I use mbed to SHA-256 sign.
String Sha256Sign(String dataToSign, String enrollmentPrimaryKey){
/// Length of the dataToSign string
const unsigned dataToSignLength = dataToSign.length();
/// Buffer to hold the dataToSign as a char[] buffer from String.
char dataToSignChar[dataToSignLength + 1];
/// String to c-style string (char[])
dataToSign.toCharArray(dataToSignChar, dataToSignLength + 1);
/// The binary decoded key (from the base 64 definition)
unsigned char decodedPSK[32];
/// Encrypted binary signature
unsigned char encryptedSignature[32];
/// Base 64 encoded signature
unsigned char encodedSignature[100];
Serial.printf("Sha256Sign(): Registration Id to sign is: (%d bytes) %s\n", dataToSignLength, dataToSignChar);
Serial.printf("Sha256Sign(): DPS group enrollment primary key is: (%d bytes) %s\n", enrollmentPrimaryKey.length(), enrollmentPrimaryKey.c_str());
// Need to base64 decode the Preshared key and the length
const unsigned base64DecodedDeviceLength = decode_base64((unsigned char*)enrollmentPrimaryKey.c_str(), decodedPSK);
Serial.printf("Sha256Sign(): Decoded primary key is: (%d bytes) ", base64DecodedDeviceLength);
for(int i= 0; i<base64DecodedDeviceLength; i++) {
Serial.printf("%02x ", (int)decodedPSK[i]);
}
Serial.println();
// Use mbed to sign
mbedtls_md_type_t mdType = MBEDTLS_MD_SHA256;
mbedtls_md_context_t hmacKeyContext;
mbedtls_md_init(&hmacKeyContext);
mbedtls_md_setup(&hmacKeyContext, mbedtls_md_info_from_type(mdType), 1);
mbedtls_md_hmac_starts(&hmacKeyContext, (const unsigned char *) decodedPSK, base64DecodedDeviceLength);
mbedtls_md_hmac_update(&hmacKeyContext, (const unsigned char *) dataToSignChar, dataToSignLength);
mbedtls_md_hmac_finish(&hmacKeyContext, encryptedSignature);
mbedtls_md_free(&hmacKeyContext);
Serial.print("Sha256Sign(): Computed hash is: ");
for(int i= 0; i<sizeof(encryptedSignature); i++) {
Serial.printf("%02x ", (int)encryptedSignature[i]);
}
Serial.println();
// base64 decode the HMAC to a char
encode_base64(encryptedSignature, sizeof(encryptedSignature), encodedSignature);
Serial.printf("Sha256Sign(): Computed hash as base64: %s\n", encodedSignature);
// creating the real SAS Token
return String((char*)encodedSignature);
}
|
72,031,334 | 72,031,639 | MIDI Files in Hex Value | I am a beginner in programming
Is there a way to read a midi file in its hex numbers?
I searched the internet that midi files are composed of headers and their contents are in hex numbers like
4D 54 68 64 0A ....
So, what is the best way to extract those hex numbers from a midi file? If there is a C++ library to do this? (I want to write the program in C++ language)
For context, I want to put these hex numbers into an array and replace some of those hex numbers (of course according to the midi file format, so the midi file isn't corrupted) and save it back into a midi file. Like doing some kind of steganography
| Let me tell you a secret: There are no hex numbers inside your computer. There are also no decimal numbers. All numbers in your computer are stored as binary. Whenever you write a decimal number like 95 in your code, what C++ does is convert it into binary internally and write it to disk as 1011111.
As such, the problem you're trying to solve needs to be re-phrased. You do not want to read hex numbers, but rather, you want to specify a number as hex in your code (instead of as decimal like usually).
There are various ways to specify a hex number. You could use a calculator to convert the number from hex to decimal, then specify that decimal number in your code (e.g. hex number 4D is 4 * 16 + 13 == 77. So when you've read a number, you can then do if (theNumber == 77) ...).
However, since writing numbers in decimal and hexadecimal is a common thing in programming, C++ actually has a way built in to write hexadecimal numbers. You write your hexadecimal number with a 0x at the start. So to write 77 in hex, you would write 0x4D. So once you've read the number from the file, you would do something like if (theNumber == 0x4D) ....
There are other bases in which you can specify a number in C++. There is 0b for binary numbers (so to specify the number exactly how it will be on disk), and if a number starts with just a 0, C++ thinks it is in octal. So be careful and don't prefix your decimal numbers with zeroes! Because 010 == 8, it's not 10 !
As to actually reading the data from the file, you do that using the fread() function.
|
72,031,942 | 72,032,204 | malloc(): corrupted top size, but I am using delete[] | void merge_sort(int* arr, int start, int stop){ // [start; stop]
int min_array_size = 8;
std::cout << start << " " << stop << std::endl;
if ((stop - start + 1) > min_array_size){
merge_sort(arr, start, start + ((stop-start+1) / 2) - 1);
merge_sort(arr, start + ((stop-start+1) / 2), stop);
std::cout << "merging: " << start << " " << stop << std::endl;
int left_index = start;
int right_index = start + ((stop-start+1) / 2);
int* new_arr = new int[stop-start + 1];
std::cout << "New_arr created!\n";
for (int i = start; i <= stop; i++){
if (arr[left_index] < arr[right_index]){
new_arr[i] = arr[left_index];
left_index++;
}
else {
new_arr[i] = arr[right_index];
right_index++;
}
if (left_index == start + ((stop-start+1) / 2)){
i++;
for (int j = i; j <= stop; j++, i++){
new_arr[j] = arr[right_index++];
}
}
if (right_index > stop){
i++;
for (int j = i; j <= stop; j++, i++){
new_arr[j] = arr[left_index++];
}
}
}
for (int i = start; i <= stop; i++){
arr[i] = new_arr[i];
std::cout << "arr[" << i << "] = " << arr[i] << std::endl;
}
delete[] new_arr;
std::cout << "memory cleaned!\n";
}
else{
selection_sort(arr + start, (stop - start + 1));
for (int i = 0; i < (stop - start) + 1; i++){
std::cout << arr[i + start] << " ";
}
std::cout << std::endl;
}
}
Can someone please tell me why it says the following if I clean memory with delete[] new_arr?
malloc(): corrupted top size
I really can't understand why it is so.
Here is my insertion_sort() code:
void selection_sort(int* arr, size_t size){
for (int i = 0; i < size - 1; i++){
int min_index = i;
for (int j = i + 1; j < size; j++){
if (arr[j] < arr[min_index]){
min_index = j;
}
}
if (min_index != i){
std::swap(arr[i], arr[min_index]);
}
}
}
https://godbolt.org/z/Wj56MM349
| You're overflowing your heap allocations, corrupting the heap, and breaking things eventually. The problem is:
You allocate an array with stop - start + 1 elements (meaning valid indices run from 0 to stop - start.
In the subsequent loop (for (int i = start; i <= stop; i++){), you assign to any and all array indices from start to stop (inclusive on both ends).
If start is not 0, then assignment to new_arr[stop] is definitely an out-of-bounds write; the larger start gets, the more invalid indices you'll see.
The problem would rarely occur as a result of a single call (the heap metadata being corrupted would be for a subsequent heap element, not the one containing new_arr), but with the recursive calls you have plenty of opportunities to do terrible things to the heap and break it faster. Even a single such out-of-bounds write puts you in nasal demons territory, so you need to fix your code to avoid doing it even once.
|
72,032,281 | 72,032,543 | Aggregate class and non-viable constructor template | As we know, in C++20 a class that has a user-declared constructor is not aggregate.
Now, consider the following code:
#include <type_traits>
template <bool EnableCtor>
struct test {
template <bool Enable = EnableCtor, class = std::enable_if_t<Enable>>
test() {}
int a;
};
int main() {
test<false> t {.a = 0};
}
Neither GCC nor CLang compile this code. So, the class is not an aggregate, despite the fact that there is no instantiated constructor here.
Is the constructor template considered to be a "declared constructor"? What does the Standard say about such a situation?
| The definition of aggregate has changed a lot, but the relevant part here has been pretty constant. The C++20 wording in [dcl.init.aggr] says:
An aggregate is an array or a class ([class]) with
no user-declared or inherited constructors ([class.ctor]),
no private or protected direct non-static data members ([class.access]),
no virtual functions ([class.virtual]), and
no virtual, private, or protected base classes ([class.mi]).
Note that it just says no declared constructors, period. Not something subtle about whether or not the constructor is viable for a particular specialization of a class template. Just none at all.
So given something like this:
template <bool B>
struct X {
int i;
X(int i) requires B;
};
X<false> still isn't an aggregate, even though its only declared constructor isn't viable for that specialization. Doesn't matter. Aggregate-ness is a property of declarations only.
|
72,032,458 | 72,032,525 | How to detect non IEEE-754 float, and how to use them? | I'm writing classes for basic types, so that code is logically the same on multiple platforms and compilers (like int_least16_t for int). For fun! (I'm still a student.)
And I read this:
float [...] Matches IEEE-754 binary32 format if supported.
And what's worse:
Floating-point types MAY support special values:
∞, NaN or -0
Which means that float MAY be unsigned... [edit: Yes it's difrent thing, but there is no: ",but must suport negative numbers". Yo, with out things like this in standart it may not suport normal 0...(I don't have specyfication.) see]
I know it's like with __int128, and the standard is just a standard,
but still...
IEEE-754 is from 1985, but some machines can be weird,
and some legacy hardware doesn't have a floating unit.
As I understand, float is mandatory (not optional like int16_t),
but can be in any standard, and any set of values can be possible?
Only thing we have are some macros (<cfloat>):
FLT_MIN, FLT_MAX - Even if FLT_MIN = IEEE-754::FLT_MIN, float can be non IEEE-754.
For example float with: flipped exponent with fraction...
FLT_RADIX - Base system? If so, can help to write the exact value. But still, float can be 3 bit or 200 bit (in size)...
FLT_EPSILON - (from 1 to next) We might use it (with base) to check fraction size...
FLT_MANT_DIG - Is it "mantissa" digits / fraction size?
FLT_MAX_EXP - Exponent filled with 1... in IEEE-754,
but outside can be a random number?
If float is like IEEE-754 (sign, exponent, fraction), then it's easy,
but if -0 and NaN are optional then it MAY be different.
Because I can't tell them apart, I can't use bit representation
(in a safe manner). And if ∞ is optional, float is no longer a safe type.
The only way out I see is to add macro to compiler.
I know it's a theoretical problem, but I'm interested if there is any check possible or we all write implementation dependent code, when we use the float keyword?
Edit 2022 May 04:
I came up with this:
User eg. code:
//User eg. code:
int main()
{
float_M a = 1f;
float_M b = 0f;
std::cout << a/b; //should output infinty (IEEE-754)
}
//Code:
class float_M
{
public:
#ifdef __STDC_IEC_559__
float data;
//...
float_M operator/(float_M x){return float_M(data/x.data);}
//...
#else
/*union{
float data;
struct{//For noSign case ("absolutly catastrofic" case)
uint_least8_t sign : 1;
uint_least8_t exponent : 8;
uint_least32_t fraction : 23;
}
}*/ //no noSign case
float data;
//...
float_M operator/(float_M x){return divide(this, x);}
//funtion pointer alert!
static /*const (1*) */ float_M (*divide)(float_M a, float_M b) =
/*std::numeric_limits<float>::is_signed ?(*/
std::numeric_limits<float>::has_infinity ?(
std::numeric_limits<float>::has_quiet_NaN ?(
[]{return float_M(a.data/b.data);}
): &_divide_noNaN
): &_divide_noNaN
/*): &_divide_noSign*/
//...
#endif
}
It's ugly (have funtion pointer), but prevents unnesesery jumps at runtime. I hope c++23 will have better macros.
Also, more links:
About Floating-Point Arithmetic
User-defined literals
No const funtion pointers (1*)
Follow-up: Can floats not suport negative
| In C++, the value of std::numeric_limits<T>::is_iec559 shall be true for all floating-point types T "if, and only if, the type adheres to ISO/IEC/IEEE 60559" and ISO/IEC/IEEE 60559:2011 is the same as IEEE 754-2008, so:
#include <iostream>
#include <limits>
int main() {
std::cout << std::boolalpha << std::numeric_limits<float>::is_iec559 << '\n';
}
Note: As noted in the comments, some implementations may still report true for this constant even though their floating point types are not following the IEEE 754-2008 standard to the letter.
For example, in gcc, you can compile with the options -Ofast or -ffast-math which in turn sets a number of options which can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions.
In C99 (and later), there are conditional feature macros, __STDC_IEC_559__ and __STDC_IEC_559_COMPLEX__, that, if available in your implementation, will tell you if it's conforming to IEC 60559:1989 / IEEE 754−1985.
#include <stdio.h>
int main(void) {
#ifdef __STDC_IEC_559__
puts("true");
#endif
}
Note that if __STDC_IEC_559__ is not defined, it doesn't necessarily mean that the implementation doesn't use IEEE 754 floats. It could just mean that it doesn't have these conditional feature macros. One interesting note about these macros is that if you use -Ofast or -ffast-math in gcc, they will not be defined (unlike in the C++ test).
The actual revision of the IEC / IEEE standards used changed in C11 and C17/18 and in C23 (draft) there will be a number of new macros related to floating points and it (currently) refers to ISO/IEC 60559:2020 and IEEE 754-2019 which contains minor upgrades to IEC 60559:2011 / IEEE 754-2008.
|
72,032,512 | 72,033,232 | `operator<<` on a container which works for both values and references | There is a container class container which is templated, so it can contain anything.
I want to add ability to print its contents to std::ostream so I've overriden operator<<.
However this has a drawback: if the container contains references (or pointers), the method only prints addresses instead of real information.
Please consider this simple test code which demonstrates the problem:
#include <iostream>
#include <deque>
template<typename T, bool is_reference = false>
class container {
public:
container() {}
void add(T a) { queue.push_back(a); }
friend std::ostream& operator<<(std::ostream& out, const container<T, is_reference>& c) {
for (const T& item : c.queue) {
if (is_reference) out << *item; else out << item;
out << ",";
}
return out;
}
private:
std::deque<T> queue;
};
int main() {
//Containers
container<int*, true> myContainer1;
container<int> myContainer2;
int myA1(1);
int myA2(10);
myContainer1.add(&myA1);
myContainer1.add(&myA2);
myContainer2.add(myA1);
myContainer2.add(myA2);
std::cout << myA1 << std::endl;
std::cout << myA2 << std::endl;
std::cout << myContainer1 << std::endl;
std::cout << myContainer2 << std::endl;
return 0;
}
I had an idea to provide an extra is_reference boolean in the template for adjusting the operator<<.
However this causes an early compiler error, in case I have value type container(s).
How can I make this work?
If I change the printer line to
out << item << ",";
The code compiles and prints this:
1
10
0x7ffd77357a90,0x7ffd77357a94,
1,10,
Obviously my goal is to have this result:
1
10
1,10,
1,10,
(How) can I achieve this easily?
| You can use SFINAE to select an overload based on whether std::is_pointer<T>::value is true or false. This works already with C++11:
#include <iostream>
#include <deque>
template<typename T>
class container {
public:
// container() {} // dont define empty constructor when not needed
// or declare it as = default
void add(const T& a) { queue.push_back(a); } // should take const&
template <typename U = T, typename std::enable_if< std::is_pointer<U>::value,bool>::type=true>
friend std::ostream& operator<<(std::ostream& out, const container<T>& c) {
std::cout << "is pointer\n";
}
template <typename U = T, typename std::enable_if< ! std::is_pointer<U>::value,bool>::type=true>
friend std::ostream& operator<<(std::ostream& out, const container<T>& c) {
std::cout << "is not pointer\n";
}
private:
std::deque<T> queue;
};
int main() {
//Containers
container<int*> myContainer1;
container<int> myContainer2;
std::cout << myContainer1 << std::endl;
std::cout << myContainer2 << std::endl;
}
Output:
is pointer
is not pointer
Since C++17 you can use constexpr if. Also since C++17 there is std::is_pointer_v and since C++14 there is std::enable_if_t, both would make the code a little less verbose.
|
72,032,754 | 72,033,059 | Unexpected Result with Cpp Vector insert | I have the following function
void rotate(vector<int>& nums, int k) {
int original_size = nums.size();
k = k%original_size;
nums.insert(nums.begin(), nums.end()-k, nums.end());
nums.resize(original_size);
}
For these inputs, I get the proper result
[1,2,3,4,5,6,7]
3
----
[5,6,7,1,2,3,4]
============
[-1]
2
----
[-1]
However, for the input below, I am getting the wrong result.
[1,2,3]
1
----
[2,1,2]
It seems that the nums.insert(nums.begin(), nums.end()-k, nums.end()); properly works on the first two example, but not on the third one. I can't think of why is that.
| You may not use insert with first and last being iterators to the same vector. That is because inserting elements invalidates iterators. From cppreference (overload 4):
The behavior is undefined if first and last are iterators into *this.
You can use std::rotate to rotate elements in a vector.
|
72,032,820 | 72,038,604 | How do you deploy/package a CMake project with Visual Studio? | I'm currently working on a small CMake project with visual studio and I'm wanting to distribute my current build but I have no clue how to, when testing the app on another system it would error saying what I'm guessing were runtime dll's that were missing. I can't find anything online about it, and the official CMake tutorial didn't work for me. Does anyone know a way to do this?
| Just like you have been told in the comments, the proper way to distribute an application on Windows is to use VC redistributable package. But if one wants to create an independent "bundle" CMake can help with it. It has a module which helps to bring the necessary dlls wherever needed. You need to understand and plan how your resulting bundle will look like and adapt the paths accordingly. I will just show you how to bring the dlls to the current binary directory with the help of the said module:
set(CMAKE_INSTALL_PREFIX "${CMAKE_CURRENT_BINARY_DIR}")
include(InstallRequiredSystemLibraries)
These 2 lines will make sure that you have an install target by building which the dlls required will be copied (installed) to the ${CMAKE_INSTALL_PREFIX} path. That would be your start from which you can proceed further with any customization you need to make.
|
72,033,124 | 72,033,354 | Selecting files with folder using QFileDialog | I have a use case in an application using C++ and Qt (on windows 10). The application uses 7zip.exe as a subprocess to uncompress the files in a selected folder. I need to use QFileDialog to select a folder, and get all the files with extension .zip and .7z, to be selected automatically and then uncompress them using QProcess and display them in the output.
I came up with this code snippet. For selecting the files with selected folders.
void MainWindow::on_browseButton_clicked()
{
QFileDialog d(this);
d.setFileMode(QFileDialog::Directory);
d.setNameFilter("*.zip");
if (d.exec())
qDebug () << d.selectedFiles();
}
but this code does not run, and it displays just the folder name not with no files selected. Could anyone suggest where I am doing wrong.
|
it displays just the folder name not with no files selected.
That is what it is supposed to return. You asked it to display a dialog to select a folder, so that is all you can select. selectedFiles() will return the path to the selected folder, per the documentation:
https://doc.qt.io/qt-5/qfiledialog.html#FileMode-enum
Constant
Value
Description
QFileDialog::Directory
2
The name of a directory. Both files and directories are displayed. However, the native Windows file dialog does not support displaying files in the directory chooser.
https://doc.qt.io/qt-5/qfiledialog.html#selectedFiles
Returns a list of strings containing the absolute paths of the selected files in the dialog. If no files are selected, or the mode is not ExistingFiles or ExistingFile, selectedFiles() contains the current path in the viewport.
After the dialog has closed and exec() has returned, you will then need to iterate that folder yourself to discover .zip and .7z files in it.
An easier way to handle the dialog is to use QFileDialog::getExistingDirectory() instead. You can construct a QDir from the selected folder, and then use the QDir::entryList() method to search for zip files in the folder.
See How to read all files from a selected directory and use them one by one?.
For example:
void MainWindow::on_browseButton_clicked()
{
QDir directory = QFileDialog::getExistingDirectory(this);
QStringList zipFiles = directory.entryList(QStringList() << "*.zip" << "*.7z", QDir::Files);
foreach(QString filename, zipFiles) {
// do whatever you need to do
}
}
|
72,034,789 | 72,046,722 | Artefacts on OpenGL rendering seemingly specific to hardware | I am currently writing a graphics engine for OpenGL in C++. Here's the source if you're interested: https://github.com/freddycansic/OpenGL
These are the results when rendering a cube with a solid colour or a texture on my laptop (Ryzen 5500U, integrated Radeon graphics):
https://imgur.com/a/A50DHgW
These are the results when rendering the same on my desktop (Ryzen 5 2400G, NVIDIA 1060):
https://imgur.com/a/DQrGsZ8
As you can see artefacts begin appearing when rendering using a solid colour on my desktop.
When rendering more than 1 texture I run into more issues:
Laptop working as normal: https://imgur.com/a/YFsXnE3
Desktop 2 textures merging together?: https://imgur.com/a/5itdYHA
The general code for reproducing this is as follows
Shader code:
Vertex shader:
#version 330 core
layout(location = 0) in vec4 a_Position;
layout(location = 1) in vec4 a_Color;
layout(location = 2) in vec2 a_TexCoord;
layout(location = 3) in float a_TexID;
out vec4 v_Color;
out vec2 v_TexCoord;
out float v_TexID;
uniform mat4 u_ViewProj;
void main() {
gl_Position = u_ViewProj * a_Position;
v_Color = a_Color;
v_TexCoord = a_TexCoord;
v_TexID = a_TexID;
};
Fragment shader:
#version 330 core
out vec4 color;
in vec4 v_Color;
in vec2 v_TexCoord;
in float v_TexID;
uniform sampler2D u_Textures[32];
void main() {
int index = int(v_TexID);
if (index < 0) { // if index < 0 do a color
color = v_Color;
}
else { // else do a texture
color = texture(u_Textures[index], v_TexCoord);
}
};
Create vertex array, shader, allocate memory for vertex buffer and index buffer
unsigned int program = glCreateProgram();
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexSource, nullptr);
glCompileShader(vertexShader);
// same with fragment
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
glValidateProgram(program);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
unsigned int vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
unsigned int vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, 50000 * sizeof(Vertex), nullptr, GL_DYNAMIC_DRAW);
unsigned int ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 75000 * sizeof(GLuint), nullptr, GL_DYNAMIC_DRAW);
Enable vertex attributes for position, colour, texture coordinates and texture ID.
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 40, (const void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 40, (const void*)12);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 40, (const void*)28);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, 40, (const void*)36);
Now generate vertices and indices for a cube which end up as follows:
Texture ID of -1 denotes that we are not using a texture.
{{0, 0, 0}, {1, 0, 0, 1}, {0, 0}, -1}
// ... ommited for sanity
{{1, 1, 1}, {1, 0, 0, 1}, {1, 1}, -1}
0, 1, 2,
// ...
6, 7, 4
These vertices and indices are then stored in separate vectors on the CPU until the batch concludes when:
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Vertex) * CPUVertexBuffer.size(), CPUVertexBuffer.data());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, sizeof(GLuint) * CPUIndexBuffer.size(), CPUIndexBuffer.data());
glUseProgram(program);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, (GLsizei) CPUIndexBuffer.size(), GL_UNSIGNED_INT, nullptr);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
If anyone has seen anything like this before or knows of any reason that would be causing this I would love to hear from you.
|
int index = int(v_TexID);
if (index < 0) { // if index < 0 do a color
color = v_Color;
}
else { // else do a texture
color = texture(u_Textures[index], v_TexCoord);
}
This code is wrong in two ways. The GLSL spec clearly states in section 4.1.7:
Texture-combined sampler types are opaque types, declared and behaving
as described above for opaque types. When aggregated into arrays
within a shader, they can only be indexed with a dynamically uniform
integral expression, otherwise results are undefined.
Within the rules of the GLSL spec, a single invocation group can be as big as the whole render API call, so unless your a_TexID value isn't the same for all vertices in that render call, the results of this are undefined.
Furthermore, from section 8.1:
Some texture functions (non-“Lod” and non-“Grad” versions) may require
implicit derivatives. Implicit derivatives are undefined within
non-uniform control flow and for non-fragment shader texture fetches.
Since your texture call uses implicit derivatives, it must not be used in non-uniform control flow.
What you're trying to do here cannot be achieved within the guarantees of OpenGL 4.6.
What you could do is:
Don't use an array of sampler2Ds, use a single sampler2Darray with an array texture. Selecting the layer from the array doen't have to be a dynamically uniform expression.
Use the GL_ARB_bindless_textures extension, which also removes this restriction.
|
72,035,237 | 72,035,487 | Create a copy constructor that reverses a stack using a linked list stack implementation | linkList::linkList(linkList const& rhs){
Node *temp = rhs.top;
Node *temp_stack = rhs.top;
while(temp){
char value = temp->letter;
// push(value);
push(temp_stack->letter);
temp = temp_stack->down;
temp_stack = temp_stack->down;
// temp = temp->down;
}
}
void linkList::push(char c) {
Node* new_top = new Node(c);
new_top->down = top;
top = new_top;
}
I have a problem on my copy constructor that when I call it it, it display the link-list in reverse which make sense cause I am pushing it to the back of the new link-list. assuming that my function is working 100 percent and I cant change the function. how would I go about adding it in reverse?
I looked over couple solution in here but no pretty helpful.
| For starters declarations of these two pointers within the function
Node *temp = rhs.top;
Node *temp_stack = rhs.top;
does not make a great sense. They duplicate each other. It is enough to use one pointer to traverse the list rhs.
If you want to create a copy of the passed list then the function push is not suitable.
You could define the copy constructor the following way.
linkList::linkList( linkList const& rhs ) : top( nullptr )
{
Node **current = ⊤
for ( Node *temp = rhs.top; temp != nullptr; temp = temp->down )
{
*current = new Node( temp->letter );
current = &( *current )->down;
}
}
I hope that the constructor of the class Node sets the data member down of the created node to nullptr.
|
72,035,443 | 72,035,823 | Can I ask a running thread about how much stack it has been using? | So let's say I have created a thread, on Windows OS, for which I know that the default stack size is much more than what is needed. Can I then run the application and ask the thread about the amount of stack it actually has used so that I know how much I should set its stack size instead of the default stack size?
| Windows usually doesn't commit the entire stack, it only reserves it. (Well, unless you ask it to, e.g. by specifying a non-zero stack size argument for CreateThread without also passing the STACK_SIZE_PARAM_IS_A_RESERVATION flag).
You can use this to figure out how much stack your thread has ever needed while running, including any CRT, WinAPI or third-party library calls.
To do that, simply read the StackBase and StackLimit values from the TEB - see answers to this question for how to do that. The difference of the two values should be the amount of stack memory that has been committed, i.e. - the amount of stack memory that the thread has actually used.
Alternatively, if a manual process is sufficient: Simply start the application in WinDBG, set a breakpoint before the thread exits and then dump the TEB with the !teb command. You can also dump the entire memory map with !address and look for committed areas with usage Stack.
|
72,035,480 | 72,550,370 | Azure IoT Edge C++ module not sending device to cloud telemetry | I have written an IoT Edge C++ module that is sending the event output using the following function call:
bool IoTEdgeClient::sendMessageAsync(std::string message)
{
bool retVal = false;
LOGGER_TRACE(IOT_CONNECTION_LOG, className + "::sendMessageAsync(...) START");
LOGGER_DEBUG(IOT_CONNECTION_LOG, className + "::sendMessageAsync(...) message : " << message);
Poco::Mutex::ScopedLock lock(_accessMutex);
MESSAGE_INSTANCE *messageInstance = CreateMessageInstance(message);
IOTHUB_CLIENT_RESULT clientResult = IoTHubModuleClient_LL_SendEventToOutputAsync(_iotHubModuleClientHandle, messageInstance->messageHandle, "output1", SendConfirmationCallback, messageInstance);
if (clientResult != IOTHUB_CLIENT_OK)
{
LOGGER_ERROR(IOT_CONNECTION_LOG, className + "::sendMessageAsync(...) ERROR : " << message << " Message id: " << messageInstance->messageTrackingId);
retVal = false;
}
else
{
retVal = true;
}
LOGGER_TRACE(IOT_CONNECTION_LOG, className + "::sendMessageAsync(...) END");
return retVal;
}
The result of the function call IoTHubModuleClient_LL_SendEventToOutputAsync is always coming as IOTHUB_CLIENT_OK. My module name is MicroServer and the route configured is:
FROM /messages/modules/MicroServer/outputs/output1 INTO $upstream
I do not see the SendConfirmationCallback function being called. Also, I do not see any device to cloud message appearing in the IoT hub. Any ideas why this is happening and how to fix it?
| It turned out that I need to call this function atleast a couple of times per second
IoTHubModuleClient_LL_DoWork(_iotHubModuleClientHandle);
which I was not doing. As a result the code was not working properly. Once I started doing it. The code just worked.
|
72,035,600 | 72,036,660 | How can I fix it "comparison between signed and unsigned integer expressions [-Werror=sign-compare]" | I tried to add unsigned, but the error still occurred, cpplint swears a lot because of this, I'm just tired and want to sleep(
string MinHeap::get_binary_string(unsigned int n,
unsigned int bit_size = -1) {
stringstream stream;
string reverse_binary, binary_str;
do {
stream << n % 2;
n /= 2;
} while (n);
unsigned int sizeB = bit_size;
if (sizeB != -1 && stream.str().size() < sizeB) {
unsigned int padding_size = sizeB - stream.str().size();
while (padding_size--) {
stream << '0';
}
}
| The problem is in the expression sizeB != -1.
The variable sizeB is an unsigned int, and the expression -1 results in a signed int. Since comparing signed values to unsigned values is very often a programming error, many compilers will warn you when it happens.
In your case, the -1 is just a special value carved out of the otherwise expected range of sizes. So it's not actually a bug.
There are many ways to change the code to do the same thing while assuring the compiler that you know what you're doing.
Don't use unsigned types. There are many folks on the C++ standards committee who believe that making sizes unsigned was once a necessary evil but is now a bad programming practice. (I don't find their arguments entirely persuasive, and it's often impractical to switch to signed values without breaking existing code and library interfaces.)
Make the implicit type conversions explicit. One way to do this would be to rewrite the expression as sizeB != static_cast<unsigned>(-1). As @Phil1970 suggested, you can define a constant with your magic value as the right type, though I would probably write it as constexpr auto sizeNotSet = static_cast<unsigned>(-1);.
Express your magic value as an unsigned value. sizeB != std::numeric_limits<unsigned>::max() or sizeB != (0u - 1).
|
72,035,742 | 72,037,549 | How to initialize a variable from a class method binding C++ with Swig | I want to bind some C++ code to python thanks to swig.
In my C++ code, I initialize some important variables via class methods.
However, this kind of initialization seems to create some troubles to swig which returns Error: Syntax error - possibly a missing semicolon.
Below is a very simple example extracted from swig documentation, where I only add this kind of initialization from a method.
This example is made of 3 files (my_class.hpp ; my_class.cpp ; py_myclass.i).
my_class.hpp:
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass {
public:
float getSqr();
float getSqr(float _v);
private:
float value=2.;
};
float toto=MyClass().getSqr(3.); // the only line I added !
#endif
my_class.cpp
#include "my_class.hpp"
float MyClass::getSqr() {
return getSqr(value);
}
float MyClass::getSqr(float value) {
return value*value;
}
py_myclass.i
%module py_myclass
%{
#include "my_class.hpp"
%}
%include "my_class.hpp"
So, the only modification I made from swig documentation was to add the initialization line float toto=MyClass().getSqr(3.);.
I tried to play around a bit with it, but I always get the syntax error.
From these files, I execute swig to create wrappers.
I do it with the command line:
swig -python -c++ -o py_myclass_wrap.cpp py_myclass.i
which yields me the following error:
py_myclass.i:13: Error: Syntax error - possibly a missing semicolon.
So, is there a way to accomplish this kind of initialization with swig ?
I also tried to add the line %ignore toto; before the last %include "my_class.hpp" in the file py_myclass.i, but it seems that the ignoring was ignored itself.
| SWIG's C++ parser doesn't support that initialization syntax, it seems.
Instead, in the header use:
extern float toto;
In the .cpp file initialize it:
float toto=MyClass().getSqr(3.);
Then SWIG will only see the extern declaration since it only parses the .hpp file. Here's a run of the result:
>>> import py_myclass
>>> py_myclass.cvar.toto
9.0
>>> c=py_myclass.MyClass()
>>> c.getSqr()
4.0
>>> c.getSqr(9)
81.0
|
72,036,077 | 72,036,191 | Using a value that can be approved if the user input was null | I am still a beginner in C++ but I have tried several methods to let the user only have one chance to get a value from the user if the user pressed enter without putting any value then it prints another value that I chose.
I tried:
#include <iostream>
#include <string>
using namespace std;
int main() {
char var;
cin.get(var);
if (&var == NULL)
cout << "d";
else
cout << var;
}
Also I tried
#include <iostream>
#include <string>
using namespace std;
int main() {
string value;
while (value == null) {
cin >> value;
if (value != NULL)
cout << value << " ";
else
cout << "hello"
}
}
|
if (&var == NULL)
This test will never be true. Address of an automatic variable is never null.
A simple way to check whether a stream extraction was successful is to check the state of the stream by (implicitly) converting it to bool:
char var;
std::cin >> var;
if (std::cin)
std::cout << var;
else
std::cout << "extraction failed";
but if i just clicked an enter it will not display the "extraction failed"??
The stream extraction operator won't accept pressing enter on an empty prompt. It will wait until you input at least one character before enter. You can intentionally provide empty input by sending the EOF control character (End Of File). How to do that depends on what shell you are using. On Linux, it's typically ctrl + d while on Windows it's typically ctrl + z.
If you want the behaviour of accepting enter on empty input, then you can use the get member function as you did in the question, and check whether the input character was the newline character:
cin.get(var);
if (var != '\n')
std::cout << var;
else
std::cout << "extraction failed";
|
72,036,287 | 72,036,502 | How to left shift a character array? | #include <iostream>
#include<string>
using namespace std;
int main()
{
//for left shift geeksforgeeks should become eksforgeeksge
//for right shift geeksforgeeks should become ksgeeksforgeeks
char* original = new char[100];
cout << "enter the array\n";
cin >> original;
cout << "the array entered is " << original << endl;
int temp = 0;
for (int i = 0; original[i] != '\0'; i++) { temp++; }
cout << "the size of array is " << temp << endl;
int num;
//left shift
cout << "enter the number of digits to be left shifted\n";
cin >> num;
char* temp1 = new char[temp - num];
char* temp2 = new char[num];
int tempn= temp-num;
//storing the characters in the short std::array
for (int i = temp - num; i < temp; i++) {
temp2[i] = original[i+temp-num];
cout << temp2[i];
}
//storing the characters in the larger std::array<T, N> ;
for (int i = 0; i < temp - num; i++) {
temp1[i] = original[i];
cout << temp1[i];
}
cout << endl;
cout <<"the left shifted array is\n ";
for (int i=0; i<num;i++){
original[i]=temp2[i];
cout << original[i];
}
for (int i=0; i < temp; i++){
original[num+i]=temp1[i];
cout <<original[num+i];
}
I have tried to implement a left shift on the dynamic array. But, this does not give the correct answer. It does not display the initial characters after left shifting. The issue is in storing the new array temp2 in the original array. But I cannot figure out how to fix this. Please help.
| Given an array of 4 characters:
+---+---+---+---+
ltrs = | a | b | c | d |
+---+---+---+---+
Step 1: copy the first character to a temp variable:
const char temp = ltrs[0];
Step 2 copy slot 1 to slot 0:
+---+---+---+---+
ltrs = | b | b | c | d |
+---+---+---+---+
^ |
+---+
Step 3: keep copying until end of array:
+---+---+---+---+
ltrs = | b | c | d | d |
+---+---+---+---+
Step 4: Copy the temporary variable to the last position in the array:
+---+---+---+---+
ltrs = | b | c | d | a | <--- temp
+---+---+---+---+
Changing to a larger array size is left as an exercise for the OP.
|
72,036,295 | 72,036,554 | Initialize std::array without constexpr | void test(const std::size_t& x) {
std::array<std::string, x> arr;
}
When I compile the above code I get this error.
main.cpp: In function ‘void test(std::size_t&)’:
main.cpp:15:24: error: ‘x’ is not a constant expression
How can I get the above code to compile?
| Template arguments must always be constant expressions, and function parameters are never constant expressions. To make this code work, you could do as is suggested in the comments and use std::vector instead, or you could make your test function be a template and make x be a template parameter instead of a function parameter.
|
72,036,452 | 72,036,501 | Parametrized Template Class constructor with another template class | I am trying to initialize a Calculator with two Complex variables. Both these classes are template classes.
calculator.h
#ifndef CALCULATOR_H
#define CALCULATOR_H
template <class U>
class Calculator{
private:
U left_val;
U right_val;
public:
Calculator(){}
Calculator(U m_left_val, U m_right_val){
left_val = m_left_val;
right_val = m_right_val;
}
U add();
U subtract();
};
#endif
complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
template <class T>
class Complex{
private:
T m_real;
T m_imaginary;
public:
Complex(){}
Complex(T real = 0 , T imaginary = 0){
m_real = real;
m_imaginary = imaginary;
}
Complex operator + (const Complex& complex);
Complex operator - (const Complex& complex);
};
#endif
In my main:
Calculator<double> floatCalc(30.3, 20.7);
Calculator<int> intCalc(100, 30);
Complex<double> a(2.0, 4.0);
Complex<double> b(1.0, 2.0);
Calculator<Complex<double>> complexCalc(a, b); //This is the line in question
I am getting two compile time errors that only relate to the initialization of complexCalc and they are the same error:
In file included from main.cpp:3:
calculator.h: In instantiation of 'Calculator<U>::Calculator() [with U = Complex<double>]':
main.cpp:11:33: required from here
calculator.h:10:21: error: call of overloaded 'Complex()' is ambiguous
10 | Calculator(){}
| ^
In file included from main.cpp:2:
complex.h:11:9: note: candidate: 'Complex<T>::Complex(T, T) [with T = double]'
11 | Complex(T real = 0 , T imaginary = 0){
| ^~~~~~~
complex.h:10:9: note: candidate: 'Complex<T>::Complex() [with T = double]'
10 | Complex(){}
| ^~~~~~~
In file included from main.cpp:3:
calculator.h:10:21: error: call of overloaded 'Complex()' is ambiguous
10 | Calculator(){}
| ^
In file included from main.cpp:2:
complex.h:11:9: note: candidate: 'Complex<T>::Complex(T, T) [with T = double]'
11 | Complex(T real = 0 , T imaginary = 0){
| ^~~~~~~
complex.h:10:9: note: candidate: 'Complex<T>::Complex() [with T = double]'
10 | Complex(){}
| ^~~~~~~
I don't know what this means or how to fix it.
| The issue is that there's no way to differentiate between the zero parameter constructor of Calculator, and the two parameter constructor with default arguments. You should just remove your zero parameter constructor.
|
72,036,510 | 72,036,529 | What happens if you don't call a base class's constructor for different derived constructors with different signatures? | Say I have a base and derived class like this:
class Base {
public:
Base() { ... };
Base(int param) { ... };
};
class Derived : public Base {
public:
Derived() { ... };
Derived(int param) { ... };
Derived(int p1, int p2) { ... };
};
Note that I'm not explicitly calling any of Base's constructors for Derived's constructors. That is to say, I didn't write Derived() : Base() { ... } or Derived(int param) : Base(param) { ... }.
Do any of Base's constructors get called by default when creating an instance of Derived?
If so, does Base(int param) get called when using Derived(int param), or does Base() get called?
Put another way, does C++ always default to using a base class's constructor with the same signature as the derived class's constructor if you don't specify which constructor to use? Or does it just use the base class's default constructor?
If the former, what about when using a constructor in the derived class that doesn't have a matching constructor with the same signature in the base class, such as Derived(int p1, int p2)?
Please note this question does not relate to initialization of member variables of either class. I intentionally did not include any member variables in my pseudo-code. It specifically has to do with which constructor on the base class gets used if you do not explicitly specify a base constructor in the derived class's constructors.
| Quoting from cppreference's description of constructors and how inheritance relates to them:
Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place where non-default initialization of these objects can be specified. For bases and non-static data members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified. No initialization is performed for anonymous unions or variant members that do not have a member initializer.
(Emphasis added.)
If you do not specify an initialization of the base class subobject in your derived class's constructor's member initializer list, the base class subobject is default-initialized.
|
72,036,549 | 72,036,570 | Why does getline() not read the last int value in the line? | I have a file that contains a list of books. Each book has 4 variables delimitated by a Tab.
The variables are
Title
author
isbn
qty
and there are around 400 book entries.
I have managed to write a function that reads each input to an array and saves it to a Book object.
void loadFile() {
std::ifstream inputFile("books");
std::string bookArray[4];
std::string line;
Book book;
while (getline(inputFile, line)) {
size_t field2 = 0;
size_t field1 = line.find("\t");
for (int i = 0; i <= 3; i++) {
size_t field1 = line.find("\t" , field2);
if (field1 != std::string::npos) {
std::string str2 = line.substr(field2, field1 - field2);
bookArray[i] = str2;
}
field2 = field1 + 1;
}
book.setTitle(bookArray[0]);
book.setAuthor(bookArray[1]);
book.setIsbn(bookArray[2]);
book.setQty(stoi(bookArray[3]));
std::cout << "Book: " <<book.getTitle <<'\t'<< book.getQty<< " records.\n";
}
but the function seems to not pick up the qty numbers at the end of each line. Everything else seems to be fine except the qty numbers. I cant find what's wrong with the function.
I have tried implementing the same getline() function with a '\t' delimitator argument like so:
while(getline(input, line, '\t')) {
The output just read the title of the first line and stopped there. I know the first function works.
Why is it not picking up the qty values?
The books file format is as follows:
A First Look at Graph Theory Clark John; Holton Derek Allan 9788170234630 5
A Practical Approach To Data Structures And Algorithms Sanjay Pahuja 9788122420678 7
A Practical Approach to High-Performance Computing Sergei Kurgalin; Sergei Borzunov 9783030275587 6
A Practical Guide to UNIX for Mac OS X Users Mark G. Sobell; Peter Seebach 9780321629982 5
A River Marc Martin 9781452162256 4
Total Noob here so I apologize if my code is awkward.
| The reason is that there's (likely) no tab character at the end of the line after the qty. So when you call line.find("\t", field2) the 4th time, it returns string::npos and you don't store anything in bookArray[3]
The best fix is probably to put an else there with the if:
} else {
std::string str2 = line.substr(field2, std::string::npos);
bookArray[i] = str2;
break; // there can be no more fields on the line
be aware that if you have a line with fewer than 4 fields, the elements of bookArray for the unfound fields will not be touched (so will continue to have values from the previous line)
|
72,036,711 | 72,036,761 | Is it possible to capture return value of function used in std::call_once? | Suppose I have a function returning an expensive object and I want it to call exactly once while having an access to return value of the function.
Is this achievable with std::once_flag and std::call_once or I need to go with boolean flags, etc..?
Simple example:
using namespace boost::interprocess;
shared_mempry_object openOrCreate(const char* name)
{
shared_memory_object shm(open_or_create, name, read_write);
return shm;
}
I there a way to call this function from some routine and ensure only calling once with mentioned primitives while maintaining return value?
| Simply use a static function variable.
using namespace boost::interprocess;
shared_mempry_object& openOrCreate(const char* name)
/// ^ return by reference to prevent copy.
{
static shared_memory_object shm(open_or_create, name, read_write);
// ^^^^^^ Make it static.
// This means it is initialized exactly once
// the first time the function is called.
//
// Because it is static it lives for the lifetime
// of the application and is correctly destroyed
// at some point after main() exits.
return shm; // return a fererence to the object
}
You can add some wrapper to guarantee clean-up at the end of the application.
|
72,036,882 | 72,037,001 | What is correct way to compare 2 doubles values? | There are a lot of articles, PhD publications, books and question here on this topic, still my question will be pretty straightforward.
How can we improve this or workaround without writing dozens of ifs?
Suppose I have 2 doubles;
double d1 = ..;
double d2 = ..;
The most naïve think we can try to do is to try if(d1==d2) // baaaad!!!, as we know we can fail on precision mismatches on very close values.
Second naïve thing can be if(std::abs(d1-d2) < std::numeric_limits<double>::epsilon())
This still fails for relatively big doubles as std::numeric_limits<double>::epsilon() described as follows:
Returns the machine epsilon, that is, the difference between 1.0 and the next value representable by the floating-point type T
Which for double is 0.00000000000000022204
So I came up with this:
double epsilon = std::max(d1,d2)/1E14; // I am ok with precision mismatch after 14th digit, regardless how big the number is.
The problem here is that for small numbers this fails, for instance this prints 0.00..00
double d = 1E-7;
std::cout<<std::fixed<<std::setprecision(20)<< d/1E14;
So the question will be is there a generic solution/workaround for this, or I should write dozens of ifs to decide my denomination properly in order not to overkill the precicion?
|
So the question will be is there a generic solution/workaround for this
There will not be a universal solution for finite precision floating point that would apply to all use cases. There cannot be, because the correct threshold is specific to each calculation, and cannot generally be known automatically.
You have to know what you are comparing and what you are expecting from the comparison. Full explanation won't fit in this answer, but you can find most information from this blog: https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ (not mine).
There is however a generic solution/workaround that side-steps the issue: Use infinite precision arithmetic. The C++ standard library does not provide an implementation of infinite precision arithmetic.
|
72,037,962 | 72,038,039 | The code is erasing just one dublicates and not another. Why so? | enter image description here
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int>v;
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
for(int i=1;i<nums1.size();i++)
{
if(nums1[i]==nums1[i-1])
nums1.erase(nums1.begin()+i);
}
for(int i=1;i<nums2.size();i++)
{
if(nums2[i]==nums2[i-1])
nums2.erase(nums2.begin()+i);
}
for(int i=0;i<nums1.size();i++)
{
for(int j=0;j<nums2.size();j++)
{
if(nums1[i]==nums2[j])
{
v.push_back(nums1[i]);
}
}
}
return v;
}
};
While I am comparing in both the vectors i am trying to erase dublicate elements. But eventually end up in erasing just one dublicate element and not another.The first three lines denotes vector after sorting and last denotes removing of dublicates
|
In the first 2 loops, you are erasing an element in a std::vector, from within a loop traversing its elements. This is a bad idea because the std::vector's size and element indices will change. A similar issue arrised when you use iterators which are invalidated by using erase. See: std::vector::erase
You can see here info how to do it correctly: What's the most efficient way to erase duplicates and sort a vector?
intersection does not access any class members (because there aren't any). It could be made into a free function, or a static method of class Solution (if it makes sense to put it in there).
Better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?
Please avoid posting images of used data. Instead copy-paste it as text so that it's easy for us to test.
|
72,038,088 | 72,038,126 | correct fix for warning: dereferencing type-punned pointer will break strict-aliasing rules? | Given:
inline uint16_t Hash3_x86_16(const void* key, int len, uint32_t seed)
{
uint32_t hash32;
Hash3_x86_32(key, len, seed, &hash32);
return (reinterpret_cast<uint16_t*>(&hash32)[1] | reinterpret_cast<uint16_t*>(&hash32)[0]);
}
What is the correct/best fix to prevent GCC from giving the following warning?
warning: dereferencing type-punned pointer will break strict-aliasing
rules
| Bit shifting:
return static_cast<uint16_t>(hash32 | (hash32 >> 16));
|
72,038,390 | 72,038,429 | How to input 2D vector correctly? | When I try to set and populate a 2D vector as follows, I couldn't input int numbers to them.
I try to input numbers usinga range-based for loop; but it doesn't finish after the expected number of loop cycles.
#include <iostream>
#include <vector>
using namespace std;
int main(){
int N;
vector<vector<int>> A(N,vector<int>(6));
cin>>N;
for(auto row_vec:A) {
for(auto x:row_vec) cin>>x;
}
return 0;
}
What is wrong with that code?
The following is my test input on the console:
[ec2-user@ip-10-0-1-187 atcoder]$ ./052
2
1 2
2 4
2 4
| When running your code on linux you for example, I got:
terminate called after throwing an instance of 'std::length_error'
what(): cannot create std::vector larger than max_size()
If you encountered this, it should have been part of the question; if not, you still should have reported more on the actual behavior you saw; whether you could input some numbers for example. "it didn't finish" is an unclear problem description. You probably meant that it kept on asking for numbers, despite you having entered the amount of numbers that you expected it to ask for already?
With the above hint, the first thing should be to check the vector initialization. You declare the overall size N, but where do you initialize that? It is only set after it is used! So it tries to allocate a more or less random, unknown amount of memory using whatever value happens to be in the memory location where N will be stored.
You need to move the reading of N before the initialization of A:
cin>>N;
vector<vector<int>> A(N,vector<int>(6));
As a side note to your shown input, note that cin doesn't distinguish between space and line break as separator; so with the fixed size of 6 of the "second level" vector, with an overall size of 2, your loop would expect 12 inputs.
Additionally, the row_vec and x variables are created as copies of the respective parts of your vector - meaning that after your reading loop, the elements in A will still all be 0, since only copies of it were set.
You have to explicitly say that you want to take references to the parts of A by declaring the loop variables as auto &.
Full code for reading N times 6 variables (and printing them to see whether it worked):
#include <iostream>
#include <vector>
int main()
{
int N;
std::cin>>N;
std::vector<std::vector<int>> A(N,std::vector<int>(6));
for(auto & row_vec:A)
{
for(auto & x:row_vec)
{
std::cin>>x;
}
}
// print A to verify that values were set from input:
for (auto const & row: A) // note the use of const & to avoid copying
{
for (auto const & cell: row)
{
std::cout << cell << " ";
}
std::cout << "\n";
}
return 0;
}
One last note: It's recommended to not use using namespace std;
|
72,038,591 | 72,040,008 | What is the use of _time64_t in MFC | Can someone explain to me what is _time34_t ? How will I use it ? I don't know how this _time64_t works. Should I use it as:
CTime::GetCurrentTime(_time34_t);
| There is no _time64_t in ATL or MFC. There is __time64_t (two leading underscores). That, however, is part of the (Universal) CRT, and not part of ATL or MFC either.
__time64_t is defined in corecrt.h as follows:
typedef __int64 __time64_t;
In other words: a 64-bit signed integer type. Values of this type are commonly interpreted to hold the number of seconds elapsed since midnight, January 1, 1970 (also known as UNIX time). It is returned e.g. by the _time64 function.
For ATL/MFC projects you can use CTime for time and timespan calculations, although you should consider using C++' std::chrono instead. It's just an all around better alternative, easier to use, more robust, and works well with timezones and calendars.
|
72,039,195 | 72,039,724 | CMake add_executable() failing to make executable and 3rd party library failing to untar | Problem Background
I am trying to incorporate UnitTest++ into my linux-based C++17 project template. I have done this on windows pretty easily, but I am running into major issues on linux for some reason.
I used Cmake 3.21 on Windows and I am currently using CMake 3.17.5 on Linux.
I downloaded the UnitTest++ source code from the UnitTest++ Github. and proceeded to throw the tar.gz into my 3rdParty folder in my ProjectTemplate. I have had major trouble getting it to build. So I have stripped out everything except for the one 3rd party library I added and the things that folder affects. So at this point all the main() functions are very simple. I am just expecting to see executables that do nothing.
Problem Points
The main executable gets made, but the unit testing executable
(testExecutable) does not get made.
The build fully finishes with no errors even though an executable
failed to be made.
The UnitTest++ 3rd party library fails to untar with no errors
output.
I have included the build output.
Why is the testExecutable not getting made? More importantly, why is my UnitTest++ failing to untar?
Directory Structure
ProjectTemplate
+3rdParty
-CMakeLists.txt (3rd party cmake)
-unittest-cpp-2.0.0.tar.gz
+build
+src
-ClassTemplate.cpp (just a plain class file - compiles fine)
-ClassTemplate.hpp (just a plain class file - compiles fine)
-main.cpp (basic int main function)
+UnitTests
-CMakeLists.txt (unit test cmake)
-UnittestcppMain.cpp (basic int main function)
-CMakeLists.txt (root cmake)
Build Output
Output from cmake generation / configure
[main] Configuring folder: ProjectTemplate
[proc] Executing command: /usr/bin/cmake3 --no-warn-unused-cli -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_BUILD_TYPE:STRING=Debug -DCMAKE_C_COMPILER:FILEPATH=/opt/rh/devtoolset-8/root/usr/bin/gcc -DCMAKE_CXX_COMPILER:FILEPATH=/opt/rh/devtoolset-8/root/usr/bin/g++ -S/path/to/ProjectTemplate -B/path/to/ProjectTemplate/build -G "Unix Makefiles"
[cmake] Not searching for unused variables given on the command line.
[cmake] -- The CXX compiler identification is GNU 8.3.1
[cmake] -- Check for working CXX compiler: /opt/rh/devtoolset-8/root/usr/bin/g++
[cmake] -- Check for working CXX compiler: /opt/rh/devtoolset-8/root/usr/bin/g++ - works
[cmake] -- Detecting CXX compiler ABI info
[cmake] -- Detecting CXX compiler ABI info - done
[cmake] -- Detecting CXX compile features
[cmake] -- Detecting CXX compile features - done
[cmake] Made it to this
[cmake] -- Configuring done
[cmake] -- Generating done
[cmake] -- Build files have been written to: /path/to/ProjectTemplate/build
output from build
[main] Building folder: ProjectTemplate
[build] Starting build
[proc] Executing command: /usr/bin/cmake3 --build /path/to/ProjectTemplate/build --config Debug --target ExecutableName -j 18 --
[build] Scanning dependencies of target ExecutableLib
[build] [ 25%] Building CXX object CMakeFiles/ExecutableLib.dir/src/ClassTemplate.cpp.o
[build] [ 50%] Linking CXX static library libExecutableLib.a
[build] [ 50%] Built target ExecutableLib
[build] Scanning dependencies of target ExecutableName
[build] [ 75%] Building CXX object CMakeFiles/ExecutableName.dir/src/main.cpp.o
[build] [100%] Linking CXX executable ExecutableName
[build] [100%] Built target ExecutableName
[build] Build finished with exit code 0
UPDATE
Thanks to 273K a solution was pointed out. I had accidentally switched my target from "All" to "ExecutableName" in VSCode. I have included a screenshot of the problem area and what it had to be set to in order to avoid this problem for future users who might be using VSCode and stumble on this question.
This is the bottom edge of VSCode, this is where the CMake extension puts it build options.
| Somehow you set --target ExecutableName, that limits the build to a single target, the main executable ExecutableName. Try to select another target, or let it unset.
|
72,039,771 | 72,039,852 | Finding the largest prime factor? (Doesn't work in large number?) | I am a beginner in C++, and I just finished reading chapter 1 of the C++ Primer. So I try the problem of computing the largest prime factor, and I find out that my program works well up to a number of sizes 10e9 but fails after that e.g.600851475143 as it always returns a wired number e.g.2147483647 when I feed any large number into it. I know a similar question has been asked many times, I just wonder why this could happen to me. Thanks in advance.
P.S. I guess the reason has to do with some part of my program that is not capable to handle some large number.
#include <iostream>
int main()
{
int val = 0, temp = 0;
std::cout << "Please enter: " << std::endl;
std::cin >> val;
for (int num = 0; num != 1; val = num){
num = val/2;
temp = val;
while (val%num != 0)
--num;
}
std::cout << temp << std::endl;
return 0;
}
| Your int type is 32 bits (like on most systems). The largest value a two's complement signed 32 bit value can store is 2 ** 31 - 1, or 2147483647. Take a look at man limits.h if you want to know the constants defining the limits of your types, and/or use larger types (e.g. unsigned would double your range at basically no cost, uint64_t from stdint.h/inttypes.h would expand it by a factor of 8.4 billion and only cost something meaningful on 32 bit systems).
|
72,040,306 | 72,043,335 | Makefile target with wildcard is not working | I have a simple project, whose folder structure is something like:
ls -R
.:
build include makefile src
./build:
./include:
myfunc.h
./src:
main.cpp myfunc.cpp
I want to compile the .cpp sources into .o object files, which should end into ./build folder. Using the GNUmake documentation and other sources (e.g. Proper method for wildcard targets in GNU Make), I wrote this makefile:
CXX := g++
CXXFLAGS += -I./include
CXXFLAGS += -Wall
OBJDIR := ./build
SRCDIR := ./src
PROGRAM = release
DEPS = myfunc.h
SRC = $(wildcard $(SRCDIR)/*.cpp)
OBJ = $(patsubst $(SRCDIR)/%.cpp, $(OBJDIR)/%.o, $(SRC))
all: $(PROGRAM)
$(PROGRAM): $(OBJ)
$(CXX) $(CXXFLAGS) -o $(PROGRAM) $(OBJ)
$(OBJDIR)/%.o: $(SRCDIR)/%.cpp $(DEPS)
$(CXX) $(CXXFLAGS) -c $< -o $@
.PHONY: clean
clean:
rm $(PROGRAM) $(OBJ)
But I get the error message: make: *** No rule to make target 'build/main.o', needed by 'release'. Stop.. I tried a lot of different ways but I cannot manage to have my .o files end up in the ./build directory. Instead, everything works if I put them in the root directory of the project. I can also make it work by specifying a rule for each object file, but I'd like to avoid that. What am I missing?
(I am using GNUmake version 4.3)
| The problem is here:
$(OBJDIR)/%.o: $(SRCDIR)/%.cpp $(DEPS)
$(CXX) $(CXXFLAGS) -c $< -o $@
See the $(DEPS)? That expands to myfunc.h. The compiler knows where to find that file (or would if this recipe were executed), because you've given it -I./include, but Make doesn't know where to find it (so it passes over this rule).
Add this line:
vpath %.h include
P.S. If you want to be really clean, you can add a variable:
INCDIR := ./include
CXXFLAGS += -I$(INCDIR)
vpath %.h $(INCDIR)
|
72,040,366 | 72,040,743 | Why the definition works at function level, but not at class level? | #include <iostream>
#include <vector>
using std::vector;
using MATRIX = vector<vector<int>>;
class Matrix {
public:
MATRIX matrix;
int row = matrix.size();
int col = matrix[0].size();
void repr() {
for (const vector<int> &sub_arr: matrix) {
for (int element: sub_arr) {
std::cout << element << ' ';
}
std::cout << '\n';
}
}
Matrix operator+(const Matrix &other) {
std::cout << row << col;
Matrix new_matrix;
if (row != other.matrix.size() || col != other.matrix[0].size()) { return {{}}; }
for (int i = 0; i < row; ++i) {
vector<int> temp_arr;
for (int j = 0; j < col; ++j) {
temp_arr.push_back(matrix[i][j] + other.matrix[i][j]);
}
new_matrix.matrix.push_back(temp_arr);
}
return new_matrix;
}
Matrix operator-(const Matrix &other) {
Matrix new_matrix;
if (row != other.matrix.size() || col != other.matrix[0].size()) { return {{}}; }
for (int i = 0; i < row; ++i) {
vector<int> temp_arr;
for (int j = 0; j < col; ++j) {
temp_arr.push_back(matrix[i][j] - matrix[i][j]);
}
new_matrix.matrix.push_back(temp_arr);
}
return new_matrix;
}
// Matrix operator*(const Matrix &other) {}
};
int main() {
Matrix matrix = {{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};
Matrix addition = matrix + matrix;
addition.repr();
}
So when I define row and col at the class level, it doesn't produce any output. But when I define it in the function, it works fine.
I don't understand why it won't work when I define it in the class level. I inserted some debug print statements, and row and col seem to be correct.
| The most "natural" solution I can see is to have a constructor taking the matrix data as an argument, and use that as the base for initializations:
class Matrix {
size_t row;
size_t col;
MATRIX matrix;
public:
Matrix()
: row{ }, col{ }, matrix{ }
{
}
Matrix(MATRIX const& data)
: row{ data.size() }, col{ data.empty() ? 0 : data[0].size() }, matrix{ data }
{
}
// ...
};
Note the check that the passed data isn't empty.
|
72,041,136 | 72,042,219 | What's the most efficient way to emplace a new element in a vector? | If I want to add a new element to a vector there are a couple of ways I can do it:
struct ZeroInitialisedType
{
int a, b, c, d, e, f;
}
std::vector my_vector;
ZeroInitialisedType foo;
foo.a = 7;
//....
my_vector.push_back(foo);
Can the compiler make it so that instead of writing into the local variable and then copying it into the vector memory at the end() that it writes it directly into the vector memory?
Does the fact that the end() pointer may change (if the vector is resized) influence whether or not it can optimize two writes to one?
What's the most efficient way to add this element to the end of the vector and write values to it?
The last question has got me thinking a bit about modern C++'s annoying quirks about value initialization. For example:
my_vector.emplace_back(); // PUSH A NEW OBJECT AT THE END
ZeroInitialisedType& ref = my_vector.back();
ref.a = 7;
//....
The problem with the above is that it zero initialises the new object on emplace_back(), then I write into it again. The same problem goes with this:
my_vector.emplace_back(ZeroInitialisedType());
// or
my_vector.push_back(ZeroInitialisedType());
If the element type of the vector isn't zero initialized then I assume the most efficient way would be to emplace_back with zero arguments, get a reference and write into it. However, when it's zero-initialized that's not the case and it becomes a problem.
Also, I'm aware that a hack could be to add a user-defined constructor to the class type, but that's not good at all to avoid zero-initialization.
| There are two independent questions related to your problem. The first one is whether an object of type ZeroInitialisedType can be constructed such that some of its members are not zero-initialized. I believe this is not possible according to the aggregate-initialization rules. A simple demo is:
struct X { int a, b, c, d, e, f; };
void f(X* ptr)
{
new (ptr) X{7}; // the same with X(7) and X{.a=7}
}
Here, all members b to f are zero-initialized in f().
You can avoid this zeroing by adding the corresponding constructor; however, the class will no longer be an aggregate:
struct Y
{
Y(int a_) : a(a_) { }
int a, b, c, d, e, f;
};
void f(Y* ptr)
{
new (ptr) Y(7);
}
Live demo: https://godbolt.org/z/3aWooxWK7.
The second question is whether the object can be constructed directly in the vector's buffer. I tried some versions with libstdc++ and only the version with "empty" emplace_back plus the back call did that.
Live demo: https://godbolt.org/z/zavvrTGj6.
I guess the cause is in the possible reallocation, which is in our case accomplished by the _M_realloc_insert call. It seems that those calls with non-empty template argument require the source to be in memory (the address is then passed via RDX). Therefore, the addressed objects need to be first stored to the stack.
The version with empty emplace_back does not have such requirements and succeeded with the direct construction in the vector's buffer. Of course, this analysis is GCC+libstdc++-related only.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.