question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,260,764 | 69,261,121 | Vulkan CommandBuffer in use after vkDeviceWait Idle | During initialization of my program I want to use some single time command buffers for image layout transitions and acceleration structure building etc.
However, I can't seem to free the command buffer once it's finished.
VkCommandBuffer AppContext::singleTimeCommandBuffer() const {
VkCommandBuffer ret;
auto al... | You aren't checking the return values of vkQueueSubmit(), vkQueueWaitIdle() or vkDeviceWaitIdle(). Are any of them failing? That could cause this error.
|
69,261,527 | 69,261,589 | C++: Does the following code lead to dangling reference? | I'm studying the rvalue reference concept in C++. I want to understand if the following code can create a dangling reference.
std::string&& s = std::move("test text");
std::cout << s << std::endl;
From my understanding, s should be a dangling reference because its assignment it binds to a return value of std::... | No it does not.
From my understanding, s should be a dangling reference because its assignment it binds to a return value of std::move
You have looked at the value categories, but not at the types.
The type of "test text" is char const[10]. This array reside in const global data.
You then pass it to move, which will ... |
69,261,655 | 69,567,372 | Issue linking and compiling C++ lib (Pcapplusplus) in SwiftUI project | I'm trying to utilize the C++ lib Pcapplusplus in my SwiftUI application through the use of objective C bridge classes. I've compiled a standalone C++ executable that makes very basic use of the pcpp library, but I'm lost on how to link and compile it in xcode. Here's the two makefiles I use to run the standalone execu... | Here are the steps to build PcapPlusPlus in a SwiftUI project:
Run PcapPlusPlus configuration script for arm64:
./configure-mac_os_x.sh --arm64
Build PcapPlusPlus:
make libs
Go to the build settings, and under "header search paths" add the PcapPlusPlus include dir
Under "other linker flags" add:
-L/usr/local/lib -... |
69,261,657 | 69,305,956 | Querying a large dataset in-browser using webassembly | For argument's sake, let's say that a browser allows 4GB of memory in WebAssembly applications. Ignoring compression and other data-storage considerations, if a user had a 3GB local csv file, we could query that data entirely in-memory using webassembly (or javascript, of course). For example, if the user's data was of... | Javascript File API
By studying the File API it turns out that when reading a file the browser will always handle you a Blob.This gives the impression that all the file is fetched by the browser to the RAM. The Blob has also a .stream() function that returns a ReadableStream to stream the very same Blob.
It turns out (... |
69,261,740 | 69,272,703 | Serialize data to std::vector<uint8_t> - Protobuf C++ | I'm stuck in a simple but hurting task: data parsing in C++. I need to serialize the data content from a Protobuf object to std::vector<uint8_t>. I've seen several examples to serialize the data to *void or char[] buffers using the SerializeToArray method, but not for what I need. I'd like to have a hand with this, tha... | The straight-forward solution is to presize the std::vector<uint8_t> to the correct size:
size_t nbytes = std::vector<uint8_t> v(proto_object.ByteSizeLong());
/* The test is necessary becaue v.data could be NULL if nbytes is 0 */
if (nbytes)
proto_object.SerializeToArray(v.data(), nbytes);
The only problem h... |
69,261,794 | 69,261,857 | Output has one extra line c++ | I am typing a program in c++ where it takes a number and does the following.
If the number is a multiple of 3 but not 5, the output is Fizz.
If the number is a multiple of 5 but not 3, the output is Buzz.
If the number is a multiple of both 5 and 3, the output is FizzBuzz.
If the number is neither a multiple of 3 o... | For loop should start from 1.
void fizzBuzz(int n) {
for(int i = 1; i <= n; i++){
if(i % 3 == 0 && i % 5 != 0) cout << "Fizz" << endl;
if (i % 3 != 0 && i % 5 == 0) cout << "Buzz" << endl;
if (i % 3 != 0 && i % 5 != 0) cout << i << endl;
if (i % 3 == 0 && i % 5 == 0) cout << "FizzBuz... |
69,261,797 | 69,307,696 | List only files where compilation errors happened | I want a list of files where compilation errors happened without duplicates. Like so:
/home/luizromario/project/src/foo.cpp
/home/luizromario/project/src/bar.cpp
I'm using Emacs's compilation mode to run gcc. Is there some way to achieve that either through gcc itself or through Emacs?
Edit: I'm running make with the... | After looking for some ideas1, here's what I found works for me:
more compilation-out | grep "error:" | sed 's/:.*//' | sort | uniq
(There are several options to do this on Emacs2).
|
69,261,967 | 69,262,104 | How can I remove the PERIOD before the number 1 in the output? | cin >> i >> e;
while ( i <= e){
cout << "." << i;
i = i + 1;
}
Example:
INPUT: 1 5
OUTPUT: .1.2.3.4.5
EXPECTED OUTPUT: 1.2.3.4.5
| I haven't tested it, but this should do what you're looking for.
int main( ) {
int input{ 0 };
int count{ 0 };
std::cin >> input >> count;
std::cout << input;
while( ++input <= count ) {
std::cout << '.' << input;
}
std::cout << '\n';
}
|
69,262,027 | 69,262,320 | Does CPath perform reference counting? | I was wondering whether ATL's CPath behaves like the underlying CString, in that an assignment will result in a ref count rather than a deep copy. I don't see anything in the docs about it, and I'm not sure how to test it. Here's some source that may be relevant, though I'm not sure:
template< typename StringType >
cl... | As you showed in the code above, the CPath is just a wrapper for CString, so it encapsulates all its properties and behavior. Logically, it uses CString reference counting.
|
69,262,332 | 69,262,394 | program to find The number of prime numbers in array using cpp | this is the problem
enter link description here
the problem in function prime but it think it is true , and i can not find solution
i submit it in codeforces but it give me .Wrong answer on test 5
:-
the input :
39
81 46 4 5 2 71 66 97 51 84 50 64 68 99 58 45 64 86 14 44 7 49 45 72 94 19 33 68 83 12 89 88 39 36 51 11 ... | This for loop
for (int j = 2; j < n; j++)
is incorrect. It seems you mean
for (int j = 2; j < arr[i]; j++)
Also you should declare the variable flag within the else statement where it is used. For example
for (int i = 0; i < n; i++)
{
if (arr[i] == 2)
{
con++;
}
else if (arr[i] > 2)
{
... |
69,262,474 | 69,262,566 | Intersection of two `unordered_set`s in C++ "not working" when in a class method but works with `set`? | What I have here is two "maps", xs and ys, which I use to store "points" in a grid.
I also have an array std::pair<int,int> arr, such that xs[x] returns all the indices in arr with x-coordinate x, and ys[y] returns all indices with y-coordinate y.
Let us have the following:
std::unordered_map<int, std::unordered_set<si... | std::set_intersection requires ordered elements.
unordered_map and _set does not provide ordered elements.
|
69,262,813 | 69,262,917 | Why don't visual studio code throw error when handle with null value? | I have the code below:
class A
{
public:
int *b;
};
int main()
{
A *a = new A();
a->b = new int(1);
cout << *a->b;
cout << "done";
return 0;
}
I run it and get the expected output 1done but when I comment the a->b = new int(1); It just print nothing. How to make it throw something for me to ide... | It is not the fault of Visual Studio Code. Your code will have undefined behavior (it might throw a segmentation fault, or it might not) if you comment out a->b = new int(3) line. See I get a segmentation fault instead of an exception about how you cannot throw an exception (which VS Code can show) when a segmentation ... |
69,263,122 | 69,263,294 | How to prefer calling const member function and fallback to non-const version? | Consider a class Bar in two versions of a library:
/// v1
class Bar
{
void get_drink()
{
std::cout << "non-const get_drink() called" << std::endl;
}
};
/// v2
class Bar
{
void get_drink()
{
std::cout << "non-const get_drink() called" << std::endl;
}
void get_drink() const
{
std::cout << "... | This seems to work:
#include <type_traits>
#include <iostream>
template<typename T, typename=void>
struct find_a_drink {
void operator()(T &t) const
{
t.get_drink();
}
};
template<typename T>
struct find_a_drink<T,
std::void_t<decltype( std::declval<const T &>()
... |
69,263,774 | 69,264,137 | Why does the first and last value in my code's output doubles? | int i = 0;
int e = 0;
cin >> i >> e;
cout << i;
while( ++i <= e ) {
cout << "." << i;
}
while ( --i >= e ){
cout << '.' << i;
}
hello everyone, can I ask for some help regarding this.
If I run my code and if I input for example:
INPUT: 1 5
MY CODE OUTPUTS: 1.2.3.4.5.5
INPUT: 5
1
MY C... | Let's discuss the first input: 1 5. When you're reaching 5 by pre-incrementing the i, it prints the value of i which is 5. then it comes back to while loop again first increments the value of i (which gets to 6) then it checks the condition where 6<=e is false so the loop breaks.
Then it goes to the second loop. it dec... |
69,263,921 | 69,263,958 | Undefined reference to constructor problem | See the below-given code
#include <iostream>
using namespace std;
class Number
{
int a;
public:
Number();
Number(int num_1) {
a = num_1;
}
void print_number(void) { cout << "Value of a is " << a << endl; }
};
int main()
{
Number num_1(33), num_3;
Number num_2(num_1);
num_2.... | In your class, you have declared the default constructor, but you have not defined it.
You can default it (since C++11) and you will be good to go:
Number() = default;
Otherwise:
Number() {}
As from @TedLyngmo liked post, both will behave the same, but the class will get different meaning as per the standard, though.... |
69,264,430 | 69,264,833 | Contradictory definitions about the Order of Constant Initialization and Zero Initialization in C++ | I have been trying to understand how static variables are initialized. And noted a contradiction about the order of constant initialization and zero initialization at cppref and enseignement.
At cppref it says:
Constant initialization is performed instead of zero initialization of the static and thread-local (since C... | When in doubt, turn to the standard. As this question is tagged with C++11, we'll refer to N3337.
[basic.start.init]/2:
Variables with static storage duration ([basic.stc.static]) or thread
storage duration ([basic.stc.thread]) shall be zero-initialized
([dcl.init]) before any other initialization takes place.
Constan... |
69,265,190 | 69,265,326 | C++ Create an object with array simultaneously with the constructor | So, I've been exploring on how to create a dynamical array with a custom template class that I made.
#include <iostream>
#include <vector>
//HOW TO SET CLASS INTO DYNAMICAL ARRAY WITH VECTOR
//CREATE A CLASS
class User{
std::string name;
public:
User(){
}
User(std::string name){
this->name = ... | Yes, you can!
User users[]{ User{ "one" }, User{ "two" } };
// Construct vector from iterator-pair:
std::vector<User> users_vector{ std::cbegin(users), std::cend(users) };
|
69,265,233 | 69,266,219 | Order a vector according to weights stored in another vector using STL algorithms | I have a vector containing instances of a class, let's say std::vector<A> a. I want to order this vector according to weights stored in a std::vector<float> weights, with weights[i] being the weight associated to a[i]; after sorting, a elements must be ordered by increasing weight.
I know how to do this explicitly, but... | Sort an index vector, then rearrange according to the result:
void my_sort(std::vector<A>& a, std::vector<float>& weights)
{
std::vector<int> idx(a.size());
std::iota(idx.begin(), idx.end(), 0);
sort(idx.begin(), idx.end(),
[&](int a, int b) { return weights[a] < weights[b]; });
auto reorder = [&](const a... |
69,265,275 | 69,265,549 | How could I check If a variable is a certain number multiple times while changing what to do if It matches? | I want to check what the variable "num" is from 0 - 15 How can I check if it is one of those numbers and what number it is so far I've got.
#include <iostream>
using namespace std;
int num = 0;
int main()
{
cout << "Number to check:";
cin >> num;
{
if num = 0;
cout << "0000";
{
if num = 2;
... | The program below does what you want.
#include<iostream>
#include <bitset>
int main() {
int num = 0;
std::cout << "Number to check: ";
std::cin >> num;
while (std::cin.fail() || num > 15 || num < 0) {
std::cout << "Error! Invalid Input \n";
s... |
69,265,335 | 69,269,907 | Disable mouse / cursor detection | I'm making a simple Pong game.
When I ran the program, all the moves are perfect (the moving are not too fast nor too slow).
However, when I move my cursor around, the movement are faster which making the game much harder.
while (enable_loop)
{
Ticks = SDL_GetTicks();
while (SDL_PollEven... | Move the keyPressed checks outside the SDL_PollEvent() loop:
while (enable_loop)
{
Ticks = SDL_GetTicks();
while (SDL_PollEvent(&any_event))
{
if (any_event.type == SDL_QUIT)
{
enable_loop = false;
}
}
// Process keyboard event
keyPressed = SDL_GetKeyboardSta... |
69,265,574 | 69,268,067 | How to convert a class declaration to a string using macros? | I need to convert my class declaration into a string and I also need the class defined. in the code below i have given an example which results in Identifier Person is undefined or Incomplete type not allowed. but if this is possible with custom macros, some code would be much appreciated.
struct Person;
std::string Pe... | You can't do that; you can't initialize Person::meta before the type is defined, and you can't define the type as part of the initializing expression.
However, you can move the initialization into the macro:
#define WITH_META(cls, body) struct cls body; std::string cls::meta = "struct " #cls #body;
WITH_META(Person, {... |
69,265,707 | 69,265,896 | Template type argument `T` where `T*` expands to `nullptr_t` | What I'm looking for is basically this:
template <typename T>
struct a {
using pointer_type = T*;
};
What I want is such X so that a<X>::pointer_type evaluates to nullptr_t. Is this possible?
Edit: This is what I actually need (the pointer_type is hidden in the signatures of the ENCODER and DECODER template argu... | You could also use std::conditional from the <type_traits> header:
#include <type_traits>
// ...
template <typename T>
struct a {
using pointer_type = typename std::conditional<std::is_same<T, std::nullptr_t>::value,
std::nullptr_t,
T*
... |
69,265,917 | 69,274,688 | Same test cases showing different answer | I have doubt regarding this min-max problem:
My code :
void miniMaxSum(vector<int> arr) {
sort(arr.begin(), arr.end());
int sum=0;
for(int i=0; i<5; i++)
sum += arr[i];
cout<<sum-arr[4]<<" "<<sum-arr[0]<<endl;
}
In other words:
void miniMaxSum(vector<int> arr) {
sort(arr.begin(), arr.end());
int min=0... | int is a 32bit integer, the problem mentions that it's possible for the answer to be greater than this. You will want to use a 64 bit integer (int64_t) for your vector and your max variables.
You should also switch to passing by reference instead of by value
void miniMaxSum(vector<int> arr) { will copy the entire array... |
69,266,652 | 69,266,854 | How i can print a number triangle in c++ | #include<iostream>
using namespace std;
int main(){
int i=1;
do{
if(i < 10){
cout<<"00"<<i<<" ";
}
else if (i < 100){
cout<<"0"<<i<<" ";
}
else {
cout<<i<<" ";
}
if(i%10 ==0){
cout<<endl;
}
i++;
}while (i <= 100);
return 0;
}
this is output
00... | You already know how to print the individual numbers, only the larger pattern is wrong. As the pattern is 2D, your code will be easier when that 2D aspect is also present in your code. What I mean: Instead of iterating i you can iterate row and column:
for (int row=0; row<10; ++row) {
for (int col=0; col<10; ++col)... |
69,266,840 | 69,267,107 | How to loop through certain Ascii characters in c++ | I only want to loop through certain Ascii characters and not all are directly next to each other . For example I only want to loop from char '1 to 7' and then from char '? to F'. I dont want to loop through '8 to >' . I have this for loop but this will include the char I don't want.
for (char i = '1'; i < 'H'; i++)
H... | Each character has a fixed ASCII value associated with it. You can refer to any character with that particular ASCII value. You can just skip the characters you do not want with an 'if' condition. You will find all the ASCII values here. Referring to your example, if you want to skip the characters from '?' to 'F', the... |
69,266,921 | 69,272,002 | Building mediapipe fails with both GCC and Clang | I am trying to build Hello World example of Mediapipe in C++. These are my exports in .bash_profile:
export PATH=$PATH:$(go env GOPATH)/bin
export GLOG_logtostderr=1
export CC=/usr/bin/clang
export CXX=/usr/bin/clang++
#export CC=/usr/bin/gcc
#export CXX=/usr/bin/g++
export BAZEL_CXXOPTS="-std=gnu++17"
then I run this... | mediapipe depends on an old version of abseil c++ that does not include a commit necessary to work on newer libstdc++ versions. So, com_google_absl in the mediapipe WORKSPACE needs an update.
|
69,267,565 | 69,268,056 | How can we get NiceMock<> behavior to apply to a single method? | When a mocked method is called without an expectation set, gmock emits a warning:
GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: getAddress(@0x563e6bbf5530 16-byte object <F0-3A 32-6B 3E-56 00-00 30-A7 BF-6B 3E-56 00-00>)
Returns: ""
NOTE: You can safely ignore t... | You can explicitly said you can have any number of call to getAddress:
EXPECT_CALL(mock, getAddress(testing::_)).Times(testing::AnyNumber());
Demo
|
69,267,575 | 69,267,847 | C++ use class with conversion operator as index into array | #include <cinttypes>
#include <type_traits>
template<typename Id, typename Value>
class sparse_set {
static_assert(std::is_integral_v<Id>, ""); (1)
static_assert(std::is_unsigned_v<Id>, "");
Value& operator[](Id id);
void push_back(const Value& value);
// class implementation left out
};
class entity... | std::is_unsigned and std::is_integral only works for primitive types, it doesn't work for classes, even if they are implicitly convertible to a type they support. You can solve this by two ways:
Create your own trait:
#include <type_traits>
// ...
using uint16 = std::uint16_t;
using uint32 = std::uint32_t;
class en... |
69,268,428 | 69,268,511 | How to pass a second vector into the function that is the third argument of sort() function from C++ STL without using global variables? | I want to pass the below function as as the third argument in sort() function from C++ STL.
bool fn(int a, int b, vector<int> v1)
{
if (v1[a]< v1[b]) return true;
else return false;
}
I want sort a vector according to the values in another vector.
sort(v2.begin(), v2.end(),fn);
How do I pass the first vector... | First, your comparator has the wrong signature. std::sort expects a callable that can be called with 2 elements.
You can use a lambda expression that captures the vector:
sort(v2.begin(), v2.end(),[&v1](const auto& a,const auto& b){ return v1[a]< v1[b]; });
I tried to write this function fn inside main in hopes that... |
69,268,516 | 69,503,643 | Is the const overload of begin/end of the range adapters underconstrained? | In C++20, some ranges have both const and non-const begin()/end(), while others only have non-const begin()/end().
In order to enable the range adapters that wraps the former to be able to use begin()/end() when it is const qualified, some range adapters such as elements_view, reverse_view and common_view all provide c... | Recent SG9 discussion on LWG3564 concluded that the intended design is that x and as_const(x) should be required to be substitutable with equal results in equality-preserving expressions for which both are valid. In other words, they should be "equal" in the [concepts.equality] "same platonic value" sense. Thus, for in... |
69,268,747 | 69,268,854 | C++ linker error for extern-declared global object | I have trouble using an extern-declared global object. As I understand it I should be able to declare an object as extern in a header file, define it in a source file, then use the object in any other source file where the header is included. However, with the following structure, I get a linker error saying that the l... | This declaration
Logger logger;
defines a variable in the global namespace.
You need to write using qualified name
#include "logger.hpp"
using namespace foo;
void Logger::log(int num) { /* Do stuff */ }
Logger foo::logger;
From the C++ 20 Standard (9.8.1.2 Namespace member definitions)
2 Members of a named namesp... |
69,268,771 | 72,947,616 | How do I use Visual Studio Code to build, debug and run existing C++ solution (.sln) from Visual Studio 2019? | I have an existing C++ solution which I have been building and running using Visual Studio 2019. I would like to build and run the application on Ubuntu using g++ and Visual Studio Code. What is the best way of achieving this? Most of the samples provided are building single .cpp file but my application consists of man... | Use CMake and generate CMakeLists.txt from .sln and included .vcxproj using https://github.com/pavelliavonau/cmakeconverter
cmake-converter -s MyProject.sln
|
69,269,261 | 69,269,633 | Using class member as key in a std::map of said class | I have a class with an enum class member variable which is intended to be used as a description of the instantiated object, there will never be two instantiated objects of the same type, example:
class A
{
enum class Type { Type1, Type2, ...} type;
}
I want to store all instantiated objects within a collection for ... | Lets consider the key features of the map
unique keys
ordererd with respect to keys
keys are const, values not
key are stored seperately from the mapped values
Your requirement is in contrast with the last bullet so now you can consider what compromise you can make with the others.
std::set<A,CustomComparator>
With... |
69,269,563 | 70,950,612 | how to acquire a structure of eax register in c++ | if i use struct, it will take up memory unlike the actual register where al and ah together make ax register and the eax register merges with the ax register. if i use union, al and ah values will be in the same place where in real, they are 2 separate registers. how can i acquire a structure of the eax register? i hav... | @Sebastian mentioned that I should combine structs and unions to get that kind of a architecture. I was not sure if nested structs and unions would but I tried and it worked:-
union {int32 eax; union {int16 ax; struct {int8 ah, al;};};} reg_eax;
Note that using a struct or union without a name works as long as a diffe... |
69,269,979 | 69,270,373 | i'm getting "timeout: the monitored command dumped core" error in c++ code of stack | There are 3 stacks stk0, stk1 and stk2. To distinguish push and pop the program is using push0, push1 and push2 for 3 stacks and similarly pop0, pop1, and pop2. Program ends with stop0, stop1 or stop2 and shows contents of stack0, stack1 or stack2 and then exits. My code works fine for all test cases accept the one i m... | Look at this part of your code:
else if(a=="stop1") {
while(!stk0.empty()) {
cout<<stk1.top()<<endl;
stk1.pop();
}
break;
}
When a is stop1, the loop will continuously rotate and stk1 will be popped and its value will be printed, but the loop won't exit because the condition is !stk0.empty(... |
69,270,119 | 69,270,757 | Convert std::vector<string> to just a std::string in C++20 using std::views | I am trying to convert a vector to a string and join with C++20(MSVC on visual studio 19 v142, c++latest).
std::vector<std::string> strings = { "1s","2s" };
auto view1 = strings | std::views::transform([](std::string num) {return std::format("{} ", num); }); // okay
auto view2 = strings | std::views::join; // okay
auto... | In the original design of views::join, it didn't just join any range of ranges, it had to be a range of reference to ranges.
This worked:
auto view2 = strings | views::join; // okay
Because strings is a range of string& (which is a reference to a range).
But this did not:
auto view3 = strings | views::transform([](std... |
69,270,633 | 69,271,349 | Behavior of If constexpr in C++ | Even having a lot a questions about this topic, I am having more and more problems. I think the problem is in understanding the meaning of certain words. All quotes below are from Cppreference
What does 'discarded' mean in the text below? I understand 'discarded' as something never compiled/touched, something that, wh... | Consider this example:
#include <iostream>
#include <string>
template <typename T>
void foo() {
T t;
if constexpr (std::is_same_v<T,std::string>){
std::cout << t.find("asd");
} else {
t = 0;
std::cout << t;
}
}
int main () {
foo<int>(); // (2)
}
When T ... |
69,270,763 | 69,270,854 | Cannot catch in the initialize list | For the following code:
#include <iostream>
struct Str
{
Str() { throw 100; }
};
class Cla
{
public:
Cla()
try : m_mem() { }
catch(...)
{
std::cout << "Catch block is called"<< std::endl;
}
private:
Str m_mem;
};
int main()
{
Cla obj;
}
I tried to catch the exception in the c... | You're contradicting yourself.
I tried to catch the exception in the catch block. But after the catch block is run
If the catch block is run, you succeeded catching the exception from the initializer list. You're just surprised by what happened next.
First, let's think about what happens when a constructor throws: th... |
69,270,929 | 69,278,195 | Is there any practical reason why std::get_if (std::variant) takes a variant argument by pointer instead of by value/&/const&? | I've never used std::get_if, and since its name is different from std::get, I don't see a reason why its argument should be a pointerΒΉ (whereas std::get has a by-reference parameter).
ΒΉIf it was named std::get too, then overload resolution would be a reason enough.
Yes, my question could be duped to the question Is i... | This is because get_if is noexcept, so an exception will never be thrown. In order to achieve this, it must return a pointer so that nullptr can be returned when the access fails.
Because it returned the pointer, it must take the pointer of the variant. If it takes the reference of variant, then it must be able to acce... |
69,271,268 | 69,718,929 | Windows Open Dialog Box hangs forever with Address Sanitizer enabled | When Address Sanitizer is enabled, the Open Dialog Box cannot be shown. It hangs forever.
Thank you.
It hangs when running hr = pFileOpen->Show(NULL);
#include <windows.h>
#include <shobjidl.h>
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
HRESULT hr = CoInitializ... | The fix is available in current VS 2022 and VS 2019
Partial workaround for older VS:
To make this occur less often, add SetProcessAffinityMask(GetCurrentProcess(), 1); at the beginning of your program. This seem to fix completely Open Dialog case, but doesn't fix more complex occurrences. (Be sure not to keep this wor... |
69,271,601 | 69,272,704 | what is the reason that its only finds "if" condition is true where no such string exist that satisfies this condition | can anyone help me with my code?
I don't understand where its making such problem.
my code is to check if a given string is valid variable or not.
My checkIdentifier function should return false for some cases and true for some cases but its only return false.
my input is abcd and its will print valid
but when my input... | its solved
Here the condition ishfakur.at(0)>='0' satisfies even when its a valid string because the ASCI values for a to z are greater than 0 so its always true. So I have changed it to ishfakur.at(0)<='9' now I am checking if its less than equals to 9 now its restricted between 0 to 9. So no chance for a valid string... |
69,271,802 | 69,272,338 | String subscript out of range in Visual Studio | I've been following Codecademy's course on C++ and I've reached the end but I'm confused with the last task.
We have to create a program which filters chosen words as 'swear words' and replaces them with whichever character chosen.
I have written the code in Visual Studio which can be seen below
main.cpp
#include <iost... | This for inner loop
for (int j = 0; j < word.size(); j++) {
if (text[i + j] == word[j]) {
match++;
}
}
does not take into account that the tail of the string text can be much less than the value of word.size(). So this for loop provokes access memory outside the stri... |
69,271,840 | 69,272,238 | Would a shared_ptr be materialized if I'm only calling a method on its object? | I have a trivial question on c++ shared_ptrs. Please consider the following pseudo code,
class Foo{
int run();
}
class Bar{
// NOTE: returns a shared_ptr, not a const ref
shared_ptr<Foo> GetFoo() const;
}
Bar bar{...};
int k = bar.GetFoo()->run();
in this scenario, when we call bar.GetFoo(), would a shared_ptr... | The rules of the language require a shared_ptr<Foo> to be materialized even if it is immediately discarded. Calling ->run() only affects when the temporary is materialized, not whether.
In practice, the rules about when the temporary is materialized are actually just rules about who has to allocate the memory for the t... |
69,272,046 | 69,311,493 | Disable or enable warnings for cppcheck using a configuration file | With clang-tidy static analyzer I can keep a file (.clang-tidy) in the root of the project with the warnings I want to activate or deactivate.
clang-tidy will look for this file (as far I know) and use the options defined there. This saves me from hard coding long command lines in CMake or Makefiles.
Is it possible to ... | You can store the configuration in a *.cppcheck file and then use the --project command line option to run the check. See the manual - Cppcheck GUI project section.
cppcheck files are normally generated by CppCheckGUI via File -> New project file. The exact syntax is undocumented but it's basically just an XML file and... |
69,273,154 | 69,273,698 | Problem while taking input using cin after detaching that thread in C++ | Code:
#include <iostream>
#include <windows.h>
#include <thread>
using namespace std;
int input(int time, int *ptr)
{
int sec = 0, flag = 0;
thread t1([&]()
{
cin >> *ptr;
sec = 0;
flag = 1;
t1.detach();
});
thread t2(... | In your case you should use atomic shared variables across threads.
The std::cin is blocking operation. In your code two seconds later doing detach for thread1. But std::cin still waiting for input...
The console window can std::cin or std::cout but not both at the same time so you need to change algorithm to avoid thi... |
69,273,240 | 69,274,294 | Iterations getting skipped in a for loop | I'm currently working on a reliability design algorithm, which I found on this video https://www.youtube.com/watch?v=uJOmqBwENB8 here. I wrote the code in c++, but I've came across a problem where in one of the loops some iterations get skipped. Here is the whole code:
#include <iostream>
#include <cmath>
#include <vec... | If you switch your break to a continue it gets your expected results.
Reliability: 0.9, Price: 30
Reliability: 0.99, Price: 60
Reliability: 0.72, Price: 45
Reliability: 0.792, Price: 75
Reliability: 0.864, Price: 60
Reliability: 0.8928, Price: 75
Reliability: 0.36, Price: 65
Reliability: 0.396, Price: 95
Reliability:... |
69,273,679 | 69,288,813 | Can this matrix calculation be implemented or approximated without an intermediate 3D matrix? | Given an NxN matrix W, I'm looking to calculate an NxN matrix C given by the equation in this link: https://i.stack.imgur.com/dY7rY.png, or in LaTeX
$$C_{ij} = \max_k \bigg\{ \sum_l \bigg( W_{ik}W_{kl}W_{lj} - W_{ik}W_{kj} \bigg) \bigg\}.$$
I have tried to implement this in PyTorch but I've either encountered memory ... | The first solution using Numba (You can do the same using Cython or plain C) would be to formulate the problem using simple loops.
import numpy as np
import numba as nb
@nb.njit(fastmath=True,parallel=True)
def calc_1(W):
C=np.empty_like(W)
N=W.shape[0]
for i in nb.prange(N):
TMP=np.empty(N,dtype=... |
69,273,730 | 69,273,831 | Why does sleep not wait, no matter how high the value entered in the parentheses is? | I'm trying to rewrite a program that I have written earlier in C++ that connects to my laptop over ssh or sftp based on what the user types, that program works fine but I am trying to write the std::cout out letter by letter with a 200ms delay in between characters.
Here's my current attempt(doesn't work):
#include <io... | If you are using c++11, you should use thread and chrono to sleep for 200ms.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <chrono>
#include <thread>
int main()
{
std::cout << "S" << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
std::cout << "... |
69,273,765 | 69,274,120 | cannot catch segmentation fault second time | I'm trying to restart the program when segmention fault occures.
I have following minimal reproducible code:-
#include <csignal>
#include <unistd.h>
#include <iostream>
int app();
void ouch(int sig) {
std::cout << "got signal " << sig << std::endl;
exit(app());
}
struct L { int l; };
static int i = 0;
int a... | The problem is that when you restart the program by calling exit(app()) from inside ouch(), you are still technically inside the signal handler. The signal handler is blocked until you return from it. Since you never return, you therefore cannot catch a second SIGSEGV.
If you got a SIGSEGV, then something really bad ha... |
69,274,713 | 69,275,363 | VS profiler, source information not available | I'm trying to use visual studio performance profiler for the first time and I'm interested in a specific function of mine which is successfully detected by the profiler. However, when I click on it I get "Source information is not available" .
How do I fix this?
All external functions from libraries are visible. Any f... | In case someone else has the same problem, I solved it by setting the "Debug Information Format" which was previously empty in my cpp file's(the file containing the functions) General Properties:
|
69,274,793 | 69,284,424 | C++ type casting / type convention | Can anyone explain what lines 5 & 7 mean?
int a;
double b = 2.3;
a = b;
cout << a << endl;
a = int(b); // <-- here
cout << a << endl;
a = (int)b; // <-- here
cout << a << endl;
| This is called C-style casting and is not recommended to be used in c++ because it can bring to precision loss. What happens here is that the double type is represented in memory as a structure holding the whole part and the floating part. And when you say a = int(someVariableNameWhichIsActuallyDouble) it takes only th... |
69,275,801 | 69,276,056 | Can't pass lambda that calls member function as C++11 thread ctor argument | I would like to pass a lambda that calls a member function as an argument to the thread constructor but have been unable to. Here's a simple example:
#include <thread>
class Foo {
void run(void func()) {
func();
}
void bar() {
return;
}
void bof() {
std::thread thread(&Foo... | Use a std::function in Foo::run()
class Foo {
void run(std::function<void()> func) {
func();
}
void bar() {
return;
}
void bof() {
std::thread thread(&Foo::run, this, [this](){ bar(); });
thread.join();
}
};
|
69,275,851 | 69,275,899 | C++ enum keyword in function parameters | What is the point of using the enum keyword in the function parameter? It seems to do the same thing without it.
enum myEnum{
A, B, C
};
void x(myEnum e){}
void y(enum myEnum e){}
Is there a difference between the two?
| In this function declaration
void x(myEnum e){}
the enumeration myEnum shall be already declared and not hidden.
In this function declaration
void y(enum myEnum e){}
there is used the so-called elaborated type name. If in the scope there is declared for example a variable with the name myEnum like
int myEnum;
then u... |
69,275,870 | 69,276,085 | Using replace with std::ranges::views | I am trying to learn ranges in C++20 using Microsoft Visual Studio 2019.
I created a function to make lowercase in a string and replace all spaces by '_'.
template <typename R>
auto cpp20_string_to_lowercase_without_spaces( R&& rng )
{
auto view = rng
| std::ranges::views::transform( ::tolower )
| s... | transform creates a non-modifiable view. Specifically, it creates a range containing objects that are manufactured as needed. They have no permanent, fixed storage, so they cannot be "replaced" with something else.
You can copy the range into a container and then execute your replace operation on the container.
|
69,275,873 | 69,276,325 | Boost X3: Can a variant member be avoided in disjunctions? | I'd like to parse string | (string, int) and store it in a structure that defaults the int component to some value. The attribute of such a construction in X3 is a variant<string, tuple<string, int>>. I was thinking I could have a struct that takes either a string or a (string, int) to automagically be populated:
... | Sadly the wording in the x3 section is exceedingly sparse and allows it (contrast the Qi section). A quick test confirms it:
Live On Coliru
#include <boost/spirit/home/x3.hpp>
namespace x3 = boost::spirit::x3;
template <typename Expr>
std::string inspect(Expr const& expr) {
using A = typename x3::traits::attribute... |
69,276,413 | 69,304,324 | Can I overwrite a const object via placement-new? | Basic.life/8 tells us that we can use the storage occupied by an object to create a new one after its lifetime has ended and use its original name to refer to it unless:
the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualif... | Apparently all it took was to look just 2 items below the part of the standard I linked to. Basic.life/10 tells us that:
Creating a new object within the storage that a const complete object with static, thread, or automatic storage duration occupies, or within the storage that such a const object used to occupy befor... |
69,276,485 | 69,276,731 | How can I initialize a 2D array with a value different than 0? | I've tried many methods and this one is one of them:
void init_table(int _table[][MAX_COLUMNS]) {
for (int i = 0; i < MAX_COLUMNS; i++) {
for (int j = 0; j < MAX_ROWS; j++) {
_table[i][j] = -1;
}
}
}
I am just trying to figure out how to initialize my array with -1 rather than 0 it ... | If you need to fill by the same value, use std::fill:
std::fill(_table, _table + MAX_ROWS*MAX_COLUMNS, -1);
Of course, if you use padding or other advanced techniques, you should take this into account and adjust your code, but this is more advanced topics and should be considered separately.
|
69,276,614 | 69,276,805 | What is this object get destructed twice? | The socket object's destructor get called twice according to the print statement on destructor. Can anyone explain me why this happens?
Log
Connection Emplaced
Socket Moved
From Handle 1
Socket Object destructed and isLive 0
Connection Object destructed
Socket Object destructed and isLive 1
Source
#include <iostream>... | In order to store an item in the unordered_map you need to create its copy for the map and try_emplace does it: the element is constructed as value_type.
So, you get another copy of the Socket object when you execute:
const auto& [connection, inserted] = connections.try_emplace("A");
If you question is more about why ... |
69,276,882 | 69,277,015 | Getting "Exited with return code -11(SIGSEGV)" when attempting to run my code | #include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> separate(string str){
string build = "";
vector<string> temp;
for(int i = 0;i < str.size(); i++){
if(str[i] != ' '){
build += str[i];
} else if(str[i] == ' '){
... | @Allan Wind is right, but to offer an alternate solution using the C++17 standard.
Iterating
Rather than use indexes, let's use a more modern for loop.
for (const char &ch : s)
Rather than:
for (size_t i = 0; i < str.size(); i++)
After all, the index is not important in this situation.
Dealing with multiple spaces
Ri... |
69,276,945 | 69,277,204 | Point raw pointer to a shared_ptr | I started programming in C++ after a 1-year break, and I am having difficulties here and there (not that I really knew it before the break).
My current problem is that I don't know how to use pointers properly.
I have the following std::vector:
std::vector<std::shared_ptr<IHittable>> world;
Where IHittable is the inte... | I think this sounds like a good fit for std::enable_shared_from_this as Remy pointed out in the comments.
I whipped up a simplified example which hopefully makes it clear how it can be used to achieve what you're after.
class Intersection;
class IHittable : public std::enable_shared_from_this<IHittable> {
public:
... |
69,276,959 | 69,277,090 | Inconsistent IsObject() property in searching through nested properties in rapidjson document | I'm having an issue where the rapidjson library appears to be inconsistent as to when it reports IsObject() as true.
Sometimes when I call value.IsObject() after retrieving a Value from a Document, it correctly reports it as an Object. But sometimes it reports what I think should be an Object as not an Object.
A toy pr... | Two issues here.
First and main:
rapidjson::Value& v = jsonDoc[p];
...
v = v[p];
Since v is not a variable, but a reference, you don't set it to a new object, but change the original object it references to, damaging it.
Use rapidjson library Pointers if you need to change the object beneath or you can use a tric... |
69,277,263 | 69,277,776 | question with while loop condition compare string | I'm trying to get the following code to work. I want it to be so that if the input of the person's name is not an "x", I want it to skip the loop and end. If not, I want it to loop. I thought the condition would be something like the following:
void printProfile()
{
//make a "cookie" or OBJECT
HealthProfile... | Change your loop condition to
while(true)
After you got the name, add a check:
if((personName == "x")
break;
|
69,277,352 | 69,277,546 | How to use Windows LLKeyboard Hook for Combination Keypresses in C++ | I have a working Windows hook to detect the simple keypress combinations of both LCTRL + x, and LCTRL + v. The only problem I have is when I press LCTRL, then release, then press x or v, my program thinks they are still being pressed together.
Here is my Hook Callback function:
HHOOK hookHandle;
KBDLLHOOKSTRUCT hookdat... | You're incorrectly checking GetAsyncKeyState's return value:
If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is se... |
69,277,476 | 69,278,093 | Can a std::unique_ptr be reassigned such that its old value is destroyed *before* the new one is constructed? | I'm interested in updating an old personal project to modern C++. I appreciate how RAII simplifies cleanup: instead of making a new object and remembering to delete it before every return point in a function, just make_unique and it will be destroyed appropriately. But I have one nitpick when comparing the generated as... | You can use unique_ptr::reset() to deterministically destroy the currently held object when you want. Update the unique_ptr with a nullptr pointer before then updating it with a new object pointer, eg:
// std::unique_ptr<int> MyClass::m_foo;
void MyClass::refresh_foo(int x) {
m_foo.reset(); // <- int is destroyed h... |
69,277,564 | 69,318,918 | Add distance field : [x,y,z,distance] from VLP-16 using ROS or velodyne driver | Velodyne lidars publish PointCloud2 messages with the fields containing :
x, type : float32
y, type : float32
z, type : float32
intensity, type : float32
ring, type : uint16
time, type : float32
However, I need to add distance field(output points with distance) because I needed this field as a research purpose.
Is it... | The best solution is not to change the velodyne driver, but since you're using ros, to leverage all the ecosystem tools built in.
For example, the velodyne publishes a sensor_msgs/PointCloud2 topic. Then internally, using C++, ROS treats any PointCloud2 msg into any PCL pointcloud type. If you're doing serious processi... |
69,277,649 | 69,277,675 | Does passing an std::optional<T> by reference actually save copying? | I know that std::optional<T&> isn't supported in the standard. This question is about whether passing std::optional<T>& has any performance advantage
Sample code (https://godbolt.org/z/h56Pj6d6z) reproduced here
#include <ctime>
#include <iomanip>
#include <iostream>
#include <optional>
void DoStuff(std::optional<std:... | If you pass actual std::optional<std::string> then yes, there would be no copy. But if you pass just std::string then temporary optional has to be constructed first, resulting in a copy of the string.
|
69,277,652 | 69,304,334 | Whenever I try to update my code in C++(VSCode) with the g++ thing, it doesn't update what I put even after deleting the old .exe file | my code looks like ^^^ (comments because i make a file for notes on a new programming language im learning to look back at to help me)
I will put g++ filename.cpp and then ./a.exe after making a change and it doesn't change the output in the terminal. So for example if I put a :) at the end of the last string, it woul... | Please make sure you are actually using the GCC Compiler and that you are not getting errors at the moment of compile your code. You can use this to check the compiler: g++ --version; if you don't have the compiler installed, it will give you an error.
Also, at the moment of compile your code, you should use the g++ in... |
69,278,066 | 69,279,263 | Unable to use gmsh from Visual Studio C++ |
I downloaded the sdk and ran the Windows related commands described here.
Then I created a new VC++ project and copied the contents of a tutorial file included with that sdk (t1.cpp).
There were compile time errors, which I fixed by including the path to gmsh.h in the include settings found in projcet->Properties->Con... | Did you add #include "gmsh.h " and add gmsh.lib in Configuration Properties > Linker > Input? For more information, you could refer to the document: Create a client app that uses the DLL.
|
69,278,186 | 69,293,190 | Opengl shader bitwise operation not working in Windows | I use an integer to use as a "filter" and pass it to a geometric shader and use a bitwise operation to get the bit values. It works in macOS, but not in Windows. To show my point, I used and modified the tutorial code in the geometric shader part in the learnopengl.com found at
https://learnopengl.com/Advanced-OpenGL/G... | As suggested by G.M., the use of glVertexAttribIPointer solves the problem.
But I use Qt and unfortunately, it seems that glVertexAttribIPointer is not available. So I changed the glVertexAttribPointer to float type instead of an integer type. So,
Changing from
glVertexAttribPointer(2, 1, GL_INT, GL_FALSE, sizeof(int),... |
69,278,755 | 69,292,749 | Linear index for a diagonal run of an upper triangular matrix | Given a NxN matrix, I would like to linearly index into its upper right triangle,
following a diagonal by diagonal pattern, starting after the main diagonal.
For example, given a 4x4 matrix
X 0 3 5
X X 1 4
X X X 2
X X X X
I'm looking for a non recursive (closed form) function mapping linear indices from 0 to 5 to (x,y... | Thanks to @loopy-walt's observation, we have an answer!
Using the result from Linear index upper triangular matrix, a transformation of the result
(i, j) |-> (j-i-1, j)
Gives the expected outcome.
Here is a C++ implementation.
#include<tuple>
#include<cmath>
// Linear indexing of the upper triangle, row by row
std::t... |
69,278,926 | 69,280,221 | Is there some STL "container" for one element on the heap? | My question:
Classes that contain only STL containers can use the Rule of Zero, and so avoid having to manually write the destructor/copies, etc.
I'm wondering if there's an STL tool (with the above property) designed for the simplest case: one element (on the heap)?
To explain when we'd want this:
Okay this problem i... | You are possibly looking for what is called deep/clone/copy/value pointer (basically a unique pointer with deep copy capabilities). There was even a proposal, don't know its actual status: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3339.pdf.
AFAIK, it has not been accepted up to now. Maybe, some external ... |
69,280,674 | 69,285,751 | co_await custom awaiter in boost asio coroutine | I am currently trying to use the new C++20 coroutines with boost::asio. However I am struggling to find out how to implement custom awaitable functions (like eg boost::asio::read_async). The problem I am trying to solve is the following:
I have a connection object where I can make multiple requests and register a callb... | I actually managed to find a solution to this. The way to do this is by using boost::asio::async_initiate to construct a continuation handler and just defaulting the handler to boost::use_awaitable. As an added bonus this way it is trivial to match it to the other async function by simply using a template argument for ... |
69,281,119 | 69,281,391 | Remove icons on buttons in QMessageBox | There is an output message with three buttons:
QMessageBox messageBox(QMessageBox::Question, tr(""), tr(""), QMessageBox::No | QMessageBox::Yes | QMessageBox::Cancel, this);
messageBox.setButtonText(QMessageBox::No, tr("1"));
messageBox.setButtonText(QMessageBox::Yes, tr("2"));
messageBox.setButtonText(QMessageBox::Can... | Could you try:
QMessageBox messageBox(this);
messageBox.addButton(tr("1"), QMessageBox::NoRole);
messageBox.addButton(tr("2"), QMessageBox::YesRole);
messageBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
auto response = messageBox.exec();
|
69,281,372 | 69,293,941 | Using SWIG to Wrap C++ Function With Default Values | I have the following C++ function in say.hpp:
#include <iostream>
void say(const char* text, const uint32_t x = 16, const uint32_t y = 24, const int32_t z = -1) {
std::cout << text << std::endl;
}
Here is my say.i:
%module say
%{
#include "say.hpp"
%}
%include "say.hpp"
Then, I built the shared library:
$ swig... | Use the following say.i file. SWIG has prewritten code for the standard integer types and needs it included to understand them. Without them, the wrapper receives the default values as opaque Python objects and doesn't know how to convert them to the correct C++ integer types.
%module say
%{
#include "say.hpp"
%}
%in... |
69,281,595 | 69,281,652 | PPP Stroustrup exercise - copy a C-style string into memory it allocates on the free store | I'm solving the following exercise (17.4) from Stroustrup's PPP book:
Write a function char* strdup(const char* ) that copies a C-style string into memory it allocates on the free store. Don't use any standard library function.
Here's my implementation, which compiles just fine. I have a question about an error messa... | A std::string does manage the memory it uses to store the string. In main you do
std::string str;
and
cstr = strdup(&str[0]);
but your strdup calls delete[] s; on the parameter.
This is what you already know. Now consider that the destructor of std::string does already clean up the memory when it goes out of scope. ... |
69,281,840 | 69,282,120 | Delete and remove a pointer from a list | I have this code (its a smol version of the code that replicates the error) and it gives a some kind of error with memory. idk just pls help me fix it. It deletes the object so there remains just the nullptr. Idk why but it doesn't want to remove the pointer from the list.
#include <iostream>
#include <list>
// casual ... | What about:
myObjs->remove_if([](auto& pObj)
{
if ( pObj->needs_delete )
{
delete pObj;
return true;
}
else
return false;
});
|
69,281,998 | 69,282,277 | Vector of Base unique_ptr causes object slicing on emplace_back(new T()) | I'm trying to pass a type as a argument to a method that will properly construct and push a object to a vector of unique_ptr, however the created object is always the Base object. This happens when using emplace_back(), the same works fine if I just instantiate the object.
Constructing the object outside the vector wor... | You have multiple data members named name in your subclasses. You probably want to assign values to the member in body_part, not declare new members that shadow it.
class body_part
{
public:
body_part() = default;
string name = "Generic";
template <class T>
void add_body_part()
{
this->body... |
69,282,015 | 69,282,087 | Declaring a class template member that belongs to all specializations | What I'm looking for is a way to say: This is the same for all specializations:
template <typename T>
struct Foo {
using id_type = unsigned int; // this does not depend on T!
};
Foo::id_type theId; // Doesn't matter what the specialization is, id_type is always the same.
I want to access id_type without having to s... | You can't have exactly what you are asking for. Foo is not a class. Foo<T> is a class, for any T.
You could have a non-template base that holds id_type
struct FooBase {
using id_type = unsigned int;
};
template <typename T>
struct Foo : FooBase{};
FooBase::id_type theId;
You could provide a default parameter for T... |
69,282,407 | 71,219,124 | Linking to TBB libraries with CMake | I have tbb downloaded and placed in my repository directory:
> tree deps/tbb/ -d
deps/tbb/
βββ bin
βββ cmake
βΒ Β βββ templates
βββ include
βΒ Β βββ serial
βΒ Β βΒ Β βββ tbb
βΒ Β βββ tbb
βΒ Β βββ compat
βΒ Β βββ internal
βΒ Β βββ machine
βββ lib
Β Β βββ ia32
Β Β βΒ Β βββ gcc4.8
Β Β βββ intel64
Β Β βββ gcc4.8
I... | Inspired by @AlexReinking answer, here is the final implementation:
project(my-cpp-service VERSION 0.1.0)
# Equivalent to command-line option of `-DCMAKE_PREFIX_PATH=...`
list(APPEND CMAKE_MODULE_PATH "deps/tbb/cmake/")
find_package(TBB REQUIRED)
add_executable(${PROJECT_NAME}
src/main.cp... |
69,282,654 | 69,282,705 | What is the correct way of freeing std::thread* heap allocated memory? | I'm declaring a pointer to a thread in my class.
class A{
std::thread* m_pThread;
bool StartThread();
UINT DisableThread();
}
Here is how I call a function using a thread.
bool A::StartThread()
{
bool mThreadSuccess = false;
{
try {
m_pThread= new std::thread(&A::DisableThread, ... |
What is the correct way of freeing
m_pThread= new std::thread(&A::DisableThread, this);
The correct way to free a non-array object created using allocating new is to use delete.
Avoid bare owning pointers and avoid unnecessary dynamic allocation. The example doesn't demonstrate any need for dynamic storage, and idea... |
69,282,858 | 69,282,948 | Friend function cannot access private members | When reading C++ Primer I encountered the following snippet (I've omitted code that I think is irrelevant):
class Message {
friend class Folder;
public:
// ...
private:
std::string contents;
std::set<Folder*> folders;
// ...
};
// ...
void swap(Message& lhs, Message& rhs) {
using std::swap;
for (auto... | void swap(Message& lhs, Message& rhs) is a friend of Message, but you try to access private members of Folder. Your last code has the same issue: friend void swap(A&, A&); is a friend of A but you try to access private members of B. friend is not transitive. Just because A is friend of B and swap is a friend of A does ... |
69,282,861 | 69,282,985 | vector's emplace_back - vector as a constructor argument | I have the following structs:
struct A{};
struct B
{
B(std::shared_ptr<A> a, int x): a_(a), x_(x){}
std::shared_ptr<A> a_;
int x_;
};
struct C
{
C(std::vector<B> v, bool c){}
};
I would like to insert an object of type C to the vector but the following code doesn't work:
std::vector<C> vecC;
vecC.em... | You forgot another pair of braces for the std::vector. Also, you need to tell emplace_back() what kind of arguments you pass it, so you need to invoke std::vector's constructor:
vecC.emplace_back(std::vector{ B{ std::make_shared<A>(), 2 } }, false);
Alternatively, don't use emplace_back() and use push_back() instead:
... |
69,283,061 | 69,283,563 | Considering that std::cout is an initialized object, why does visual studio 'not recognise its identifier' whilst setting a Watch in the debugger? | Considering that std::cout is an initialized object, why does visual studio 'not recognise its identifier' whilst setting a Watch in the debugger?
How do I view this object in memory?
Setting both std::cout and cout as watch variables returns:
[identifier "std::cout" is undefined]
[identifier "cout" is undefined]
respe... | you could create a local reference to std::cout and add a watch for that. E.g.:
auto& mycout = std::cout;
|
69,283,525 | 69,284,207 | what does the colon in asm volatile() mean | i'm not sure if i accidently modified the code a bit, but here it is (i'm a beginner to inline assembly, but quite used to assembly in a different file):-
void out8(uint16 port, uint8 data) {asm volatile("outb %0, %1" : "dN"(port) : "a"(data));}
void out16(uint16 port, uint16 data) {asm volatile("outw %0, %1" : "dN"(po... | Read the manual for the syntax, obviously. https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html.
asm asm-qualifiers ( AssemblerTemplate
: OutputOperands
[ : InputOperands
[ : Clobbers ] ])
See also https://stackoverflow.com/questions/tagged/inline-assembly for link... |
69,283,715 | 69,284,111 | C++ compiler optimisations (MSYS2 MinGW-64 bit GCC compiler used with VSCode) | I'm trying to apply the different optimisation levels (-O0, -O1, -O2, -O3 and so on) to the compilation and execution of a .cpp file.
However, I can't figure out the exact syntax I need to use and where to write the instructions (i.e. in which terminal, the VSCode terminal or the MinGW terminal)?
Any help would be much... | In this field:
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
add the optimization option:
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExte... |
69,284,009 | 69,284,010 | Dereference a double pointer (a pointer to a pointer to a value) in GDB | I'm writing a script to reverse engineer an executable. I have a situation where RAX is a pointer to a value which itself is a pointer to an object. The very first value of that object, in turn, is a pointer to a string. A visualization should clear it up:
RAX
|
| points to
|
V
Value on the stack
|
| points to
|... | Here's how I did it:
# Dereference RAX to get the value on the stack
(gdb) x/gx $rax
0x7fffffffe0d0: 0x0000555555598700
# Dereference the value on the stack to get the start of the object
(gdb) x/gx *((uint64_t*)$rax)
0x555555598700: 0x0000555555578ea0
# Dereference ... |
69,284,573 | 69,284,702 | Can we get underscores in printf instead of blank spaces while writing "%15.2f" or something like that? | #include <iostream>
using namespace std;
int main()
{
double B = 2006.008;
printf("%15.2f", B);
return 0;
}
Output:
+2006.01
with blank spaces in the beginning
I want to replace those white spaces with underscores(_). Is there any syntax in print or any direct method to do that?
My desired output:
... | As in the comments suggested you can write a function for this, but not with printf().
#include <algorithm>
#include <iostream>
std::string formatNumber(double number)
{
char buffer[15 + 1 + 2];
sprintf(buffer, "%15.2f", number);
std::string s(buffer);
std::replace(s.begin(), s.end(), ' ', '_');
... |
69,284,652 | 69,285,189 | C++20 chrono, parsing into zoned time and formatting without trailing decimals | I am writing a bit of code that intakes a string from a user, and formats it into a zoned time. The parsing code is a bit more complicated than this example, but this will reproduce problem.
This is compiled with MSVC++ compiled with /std:c++latest.
#include <iostream>
#include <string>
#include <chrono>
#include <sstr... | Just change the type of localTimeStamp to have seconds precision:
std::chrono::local_time<std::chrono::seconds> localTimeStamp;
There's also this convenience type-alias to do the same thing if you prefer:
std::chrono::local_seconds localTimeStamp;
The precision of the parsing and formatting is dictated by the precisi... |
69,284,670 | 69,284,996 | Why is a pointer used in this program instead of regular variables? | Can anybody please explain how this code functions? Pointers are kinda confusing so I need a little bit of help to understand what's happening. I know that it's calculating the sum and absolute difference but I don't get why we need pointers here. Please help.
#include <iostream>
using namespace std;
void update(int ... | You're right. This is confusing. The code is needlessly difficult, in more ways than one.
Let's look at what's happening. The function update(int *a, int *b) takes two pointers to integers as parameters. That is, when you call it, you pass the addresses of two variables that are ints. The function adds and subtracts th... |
69,284,854 | 69,285,023 | C++ Program is not finding the searched word - except the first line | Task: Create program to read given text file and print into another text file all lines containing given substring. Reading from files should be carried out line per line.
My code:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(){
string inputFileName = "inputFile.txt";
... | int found = 0;
while (getline(inputfile, line)) {
// Processing from the beginning of each line.
if(line.find(keyWord) != string::npos){
outputFile << "THE LINE THAT IS CONTAINING YOUR KEY WORD: " << "\n"
<< line << "\n";
found = 1;
}
}
if(found == 0)
{
cout << "Error. Input te... |
69,284,927 | 69,285,054 | C++ std::conditional_t wont compile with std::is_enum_v and std::underlying_type_t | I am trying to wite type traits for types that can index into e.g. an std::vector, which should include enum types because i can cast them to their underlying type.
I have written following traits so far.
#include <iostream>
#include <type_traits>
#include <cinttypes>
#include <vector>
#include <utility>
template<type... | Substitution fails because there is no std::underlying_type_t<unsigned int>.
You can specialize seperately:
#include <iostream>
#include <type_traits>
#include <cinttypes>
#include <vector>
#include <utility>
template<typename T>
struct is_unsigned_integral :
std::integral_constant<
bool,
std::is_i... |
69,285,327 | 69,285,408 | Assigning a function to a variable in C++ | What happens if you assign a function to a variable as shown below
unsigned char uchHeaderVer;
uchHeaderVer = GetCodec(Page.Version);
BYTE CWAV::GetCodec(BYTE byVersion)
{
RecorderInfoMap::iterator it;
if ((it = m_mapRecInfo.find(byVersion)) != m_mapRecInfo.end()) {
return (BYTE) ((*it).second.nCode... |
What happens if you assign a function to a variable as shown below
You aren't assigning a function to a variable. You are calling a function, and assigning the result to that variable.
You haven't shown what BYTE is, but it is very likely to be a type alias for either unsigned char (or possibly char).
You can't assig... |
69,285,443 | 69,474,719 | Add CRL number extension to CRL using OpenSSL | For some client testing I need to generate certificates and revocation lists "on the fly". I am able to setup a revocation list with the CRL number extension using OpenSSL console commands and configuration files. However I can't make this work in code.
Here are my relevant functions:
X509* g_certificate[MAX_CERTIFICAT... | You mention that you are able to setup the CRL number extension from OpenSSL command line. You should probably take a look at the source code of the particular command then.
I haven't used CRLs, but I believe you are using the ca command. Looking for NID_crl_number in its source at apps/ca.c (from OpenSSL 1.1.1g) shows... |
69,285,515 | 69,285,612 | Does lifetime of a const auto reference inside a ranged-based for loop extends to the end of the scope? | I have ran across a bit of code, that clears a deque while inside a range-based for loop. The const auto reference is still used subsequently. Here is a small reproduction.
struct Foo
{
int x;
}
deque<Foo> q1;
deque<Foo> q2;
q1.push_front({0});
q1.push_front({1});
for (const auto& ref : q1)
{
if (ref.x == 1)
... |
Does the lifetime for the reference last through the scope, or is this an undefined behaviour?
To start with, the following range-based for loop:
for (auto const& ref : q1) {
// ...
}
expands, as per [stmt.ranged]/1, to
{
auto &&range = (q1);
for (auto begin_ = range.begin(), end_ = range.end(); begin_ != end_... |
69,285,919 | 69,286,097 | Need help struct-void error: type name isn't allowed | I created a struct and void function. I want to write out age and name inside of struct xyz with the void abc. But i didn't understand i'm getting an error on case 1-2 part
type name isn't allowed
#include <iostream>
using namespace std;
struct xyz {
int age = 20;
string name = "name";
};
void abc() {
in... | You'd have to do something like this -
#include <iostream>
using namespace std;
struct xyz {
int age = 20;
string name = "name";
};
void abc() {
xyz myStruct;
int num;
cin >> num;
switch (num) {
case 1: cout << myStruct.age << endl;
return;
case 2: cout << myStruct.name << endl;... |
69,286,141 | 69,286,703 | Accessing overloaded method from a parent class | I have stumbled upon this code, and I can't understand, why do I need to specify the class I want to call the method with one argument from? What's more interesting, if I remove the second overloaded method with two parameters, everything will work fine.
class A {
public:
virtual void foo(int a) const final {};
... | Because what b sees is the overloaded instance of foo(int a, int b), which preforms name hiding, therefore foo(int a, int b) makes foo(int a) invisible from b. If you want to make foo(int a), you should specify that it should look in class A, that's why you need A::
|
69,286,582 | 69,289,045 | what is the meaning in C++ when casting both (int) and (int16_t) | I am studying a C++ code in Arduino example for reading external data.
The code use casting (int16_t) and also (int).
int16_t is fixed integer type, but I don't understand it's purpose in the code.
_vRaw[0] = (int)(int16_t)(Wire.read() | Wire.read() << 8);
Is there any difference if I write like below?
_vRaw[0] = (int... | I've written code like this before so I can explain the purpose of the cast to int16_t.
The Arduino command Wire.read() generally returns a number between 0 and 255 representing a byte read from the I2C device.
Sometimes, two of the bytes you read from a device will represent a single signed 16-bit number using Two's c... |
69,286,717 | 69,286,798 | How to understand this expression in C++ struct? | struct Task{
int value,time,deadline;
bool operator < (const Task& t1)const{
return d<t1.deadline;
}
}task[1000];
I've read this block of code of struct initialization.
the first line, initialize variables, is easy to grasp.
What about the second line? the bool operator thing. Seems like some kind ... | What you observe is called operator overloading. In this case the operator< is overloaded for class Task.
This is done in order to be able to write something like this.
Task t1{1,2,3};
Task t2{2,3,4};
if(t1 < t2) //note, the operator< is called
{
//do your thing
}
|
69,287,014 | 69,289,950 | Store memory address of local variable in global container | In my understanding it is not possible to store the address of a local memory in a global container, because the local variable will eventually be destroyed.
class AA {
std::string name;
public:
explicit AA(std::string n) : name(n) {}
std::string getName() const {
return name;
}
};
class Y {
std::vector<... |
In my understanding it is not possible to store the address of a local memory in a global container, because the local variable will eventually be destroyed.
You're starting from a flawed understanding. It's certainly a bad idea to keep the address of a local variable beyond its lifetime, but it's still possible. As ... |
69,287,136 | 69,287,471 | How to make a c++ program and will use the command line input and ls in that directory? | My system is Ubuntu 20.04. Suppose I am in project directory and this directory contains these folders/files: test, hello.txt. I wrote the following program:-
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(int argc, char* argv[]){
const char* command = "ls" + argv[1];
sys... | What you do in your code is not correct, You add two pointers, and the result you will clearly not be what you expect. Use std::string.
So your code will look like this:
#include <iostream>
#include <string>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
if(argc < 2)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.