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 |
|---|---|---|---|---|
70,318,258 | 70,318,438 | Exclamation mark in C++/CLI | I was reading this article by Microsoft on how to marshal managed classes to native and the other way round, and I came across these lines:
this->!context_node();
protected:
!context_node()
{
// method definition
}
I searched on Google and StackOverflow for the meaning of exclamation mark (!) in the above pieces of code, but I found nothing about it and so I'm asking here if anyone can shed a light on this.
Thanks in advance to anyone that will answer.
| !classname() is the finalizer.
Since these are managed classes, their lifetime is controlled by the garbage collector.
If you implement a method ~classname(), that's the Dispose method because it's C++/CLI. It's not the destructor like in plain C++. If you implement it, the compiler automatically makes your class implement IDisposable, and calls to delete from C++/CLI or to Dispose in C# will call that method.
If you implement a method !classname(), that's the Finalizer. The Garbage Collector will automatically call that method when it cleans up that object.
In the example you linked to, they also had this:
public:
~context_node()
{
this->!context_node();
}
protected:
!context_node()
{
// (Step 7) Clean up native resources.
}
So, this is a Dispose method (~), which calls the Finalizer method (!) explicitly, so that there's no code duplication. This way, one can either call delete explicitly (or use stack semantics, same thing), or wait for the garbage collector to clean it up, and either way, the native resources will be cleaned up properly. If you had any managed resources you'd clean those up in the Dispose method only, not in the finalizer. (The C++/CLI compiler knows how to implement the IDisposable pattern properly, so it knows to suppress the finalizer if the Dispose method was called.)
|
70,318,806 | 70,318,807 | Avoiding repetitive copy-paste of static_cast<size_t>(enum_type) for casting an enum class to its underlying type | I have an enum type in my code, like this:
enum class GameConsts: size_t { NUM_GHOSTS = 4 };
I find myself repeating the required static_cast to get the enum value:
Ghost ghosts[static_cast<size_t>(GameConsts::NUM_GHOSTS)];
// and...
for(size_t i = 0; i < static_cast<size_t>(GameConsts::NUM_GHOSTS); ++i) { ... }
What is the best way to avoid this repetitive static_cast?
The option of allowing implementation of a casting operator was raised in this ISO proposal discussion, but seems to drop.
Related SO question: Overloading cast operator for enum class
Davis Herring added in a comment that C++23 added: std::to_underlying which should be the answer when we have C++23 compiler support. But the question is for C++20.
| Your first option is to use a constexpr instead of an enum:
constexpr size_t NUM_GHOSTS = 4;
You can put it inside a proper context, such as GameConsts struct:
struct GameConsts {
static constexpr size_t NUM_GHOSTS = 4;
};
Then there is no need for a casting:
Ghost ghosts[GameConsts::NUM_GHOSTS];
In case you actually need an enum, as you have a list of related values that you want to manage together, then you may use unscoped enum (i.e. drop the class from the enum class and use a regular plain-old enum) but put it inside a struct to preserve the context. I will use here an example of another enum, managing several related values.
enum class GameKeys: char { UP = 'W', RIGHT = 'D', DOWN = 'X', LEFT = 'A' };
The repeated use of static_cast may happen for the above enum, in a switch-case like that:
char key_pressed;
// ...
switch(key_pressed) {
case static_cast<char>(GameKeys::UP): // ...
break;
case static_cast<char>(GameKeys::RIGHT): // ...
break;
case static_cast<char>(GameKeys::DOWN): // ...
break;
case static_cast<char>(GameKeys::LEFT): // ...
break;
}
To avoid the repeated need for static_cast you may go with:
Option 1: Use simple unscoped enum inside a struct
struct GameKeys {
enum: char { UP = 'W', RIGHT = 'D', DOWN = 'X', LEFT = 'A' };
};
And since old-style enum can cast implicitly to its underlying type, you can get away of the casting:
switch(key_pressed) {
case GameKeys::UP: // ...
break;
case GameKeys::RIGHT: // ...
break;
case GameKeys::DOWN: // ...
break;
case GameKeys::LEFT: // ...
break;
}
Option 2: Add your own conversion function
If you actually prefer, or have to use enum class you may have a simple conversion function for which the copy-paste is just calling the function, being less cumbersome than the full static_cast syntax:
enum class GameKeys: char { UP = 'W', RIGHT = 'D', DOWN = 'X', LEFT = 'A' };
// a simple "val" function - specific for our GameKeys
constexpr char val(GameKeys key) { return static_cast<char>(key); }
And:
switch(key_pressed) {
case val(GameKeys::UP): // ...
break;
case val(GameKeys::RIGHT): // ...
break;
case val(GameKeys::DOWN): // ...
break;
case val(GameKeys::LEFT): // ...
break;
}
If you choose the last option, you may want to generalize it for any type of enum, with this code:
// creating a "concept" for enums
template<typename E>
concept EnumType = std::is_enum_v<E>;
// creating a generic "val" function for getting the underlying_type value of an enum
template<EnumType T>
constexpr auto val(T value) {
return static_cast<std::underlying_type_t<T>>(value);
}
Option 3: Cast to the enum and not from the enum
As suggested by @Nathan Pierson and @apple apple in the comments, the casting can be to the enum, with this code:
char key_pressed = 'E';
// cast to the enum
GameKeys key = static_cast<GameKeys>(key_pressed);
switch(key) {
case GameKeys::UP: // ...
break;
case GameKeys::RIGHT: // ...
break;
case GameKeys::DOWN: // ...
break;
case GameKeys::LEFT: // ...
break;
default: // ignore any other keys
break;
}
This should work fine even if key_pressed is not any of the enum values, as we have a fixed enum (having a stated underlying type, note that an enum class is always fixed, even if not stated explicitly). See also: What happens if you static_cast invalid value to enum class?
|
70,318,986 | 70,327,558 | wxWidgets/C++/Code::Blocks: Failed to import font from system library | I've been making a simple app in C++/wxWidgets that just has a catalog of Garfield comix from the Internet, without the annoying ads and offers. (Don't ask me how I got access to the PNG files of each comic in the first place, because my name already explains that)
Anyway, I'm trying to make a static text with a specific font (in my case, that would be Tahoma size 8. I'm going to make it bold but for sake of simplicity I haven't done it yet). I use the following line of code to import it from the Windows internal font catalog:
wxFont *CC_FONT_Tahoma_Bold(8, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Tahoma"), wxFONTENCODING_DEFAULT);
but whenever I try that it just fails and gives the following error message (I'm using mingw-w64 8.1.0 if that helps):
error: cannot convert 'wxFontEncoding' to 'wxFont*' in initialization
I have no idea what this means and I have tried to change the font encoding to every possible value, but still no progress. Also, I am creating the font in the App's OnInit function. I have also tried to put it in a different function. Please help.
| Turns out, I just made a silly mistake.
The real code I should have used is:
wxFont *CC_FONT_Tahoma_Bold = new wxFont(8, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Tahoma"), wxFONTENCODING_DEFAULT);
|
70,319,077 | 71,465,275 | Can special member functions be defaulted if they use typedefs? | Clang compiles this fine, but GCC and MSVC complain that operator= cannot be defaulted:
#include <type_traits>
template<class T>
struct S
{
typedef typename std::enable_if<!std::is_enum<T>::value, S>::type Me;
S &operator=(Me const &) = default;
};
int main()
{
S<int> s1, s2;
s1 = s2;
}
Is this code legal? If not, would it be legal if Me had been defined as typedef S Me;?
| Given the lack of any indications to the contrary, I'm going to answer my own question and say that, as far as I've been able to find relevant clauses in the standard, I think the code is legal and thus GCC and MSVC are complaining erroneously.
As someone pointed out above, there appears to be a bug report tracking this issue.
|
70,319,094 | 70,319,303 | How to automatically adjust width for text with SDL2_TTF | I'm working on a score display for my simple 2d SDL_2 Game.
This is the part of my code where I display the speed (basically just score):
void Renderer::renderText(const char* text, SDL_Rect* destR)
{
SDL_Surface* surfaceText = TTF_RenderText_Solid(Renderer::font, text, { 255,255,255 });
SDL_Texture* textureText = SDL_CreateTextureFromSurface(renderer, surfaceText);
SDL_FreeSurface(surfaceText);
SDL_RenderCopy(renderer, textureText, NULL, destR);
SDL_DestroyTexture(textureText);
}
There is the obvious problem that if I have a width for the number "1", the text would be squished a lot of the number was "10000" etc as you would have to fit 5 characters into an SDL_Rect that is only 1 character wide.
I could multiply the width by the number of characters however that wouldn't be very accurate as different characters have different widths.
How would I solve this?
| (I only answered this because I found out how and nobody else answered)
You can do something like this.
SDL_Rect destR = { x, y, 0, 0 };
TTF_SizeText(font, text, &destR.w, &destR.h);
Basically, TTF_SizeText enables you to get the native width and height from the text with font. Then you can just multiply the height and width as you wish.
|
70,319,354 | 70,319,507 | Sum function in C++ with unknown number of arguments and types | The first part of question is create a function (Sum) with unknown number of arguments, i've done it . It works very nice. But i have the struggle in second part , argument with different type like: int, float, double ... in one function call . Any ideals i can fix my program ???
Thanks for your attention.
I think a lot people dont understand my question.
I want my program work also with different type od argument .
For example:
sum(3, int x, int y, double z) or sum(4, double x, int y, float z, double t)
cout << func(sum, 5, 1.0, 2.0, 3.0, 4.0, 5.0) << endl; it work nicely with double , as i expected .
but
cout << func(sum, 5, 1.0, 2.0, 3, 4, 5) << endl; it doesnt work
or even all numbers are integer, it's still not work as i expected , it return 0
cout << func(sum, 5, 1, 2, 3, 4, 5) << endl;
double func(double (*f) (const double*, int) , int num, ...) {
va_list arguments;
/* Initializing arguments to store all values after num */
va_start(arguments, num);
/* Sum all the inputs; we still rely on the function caller to tell us how
* many there are */
auto *array = new double[num];
for (int x = 0; x < num; x++) {
double el = va_arg( arguments, double );
array[x] = el;
}
va_end(arguments); // Cleans up the list
return f(array, num);
}
double sum(const double *array, int n) {
double result = 0;
for (int i = 0; i < n; ++i) {
result += array[i];
}
return result;
}
| The problem is you assume double as arguments, see this line:
double el = va_arg( arguments, double );
the usual solution is to provide format of the arguments passed to function, like in printf - but I suppose you don't want to do it.
I can suggest you use variadic templates like in this example:
template<typename T>
T func(T first) {
return first;
}
template<typename T, typename... Args>
T func(T first, Args... args) {
return first + func(args...);
}
int main() {
std::cout << func(5, 1.0, 2.0, 3, 4, 5) << std::endl;
std::cout << func(5, 1, 2, 3, 4, 5) << std::endl;
return 0;
}
You may change return type from T to double.
|
70,320,031 | 70,320,160 | Variadic expansion to access multi-dimensional std::array | Suppose the following multi_array structure:
template <typename type, std::size_t... sizes>
struct multi_array
{
using storage_type = typename storage_type<type, sizes...>::type;
using value_type = type;
using size_type = std::array<std::size_t , sizeof...(sizes)>;
using difference_type = std::array<std::ptrdiff_t, sizeof...(sizes)>;
using reference = value_type&;
using const_reference = const value_type&;
// ...
storage_type data_ {};
size_type sizes_ {sizes...};
}
// Example usage:
// multi_array<float, 3, 4, 5> three_dimensional_float_array;
// storage_type will be std::array<std::array<std::array<float, 5>, 4>, 3>
// size_type will be std::array<std::size_t, 3>
where:
// Helpers to create a std::array<std::array<...>> from a pack expansion.
template <typename type, std::size_t... sizes>
struct storage_type;
template <typename _type, std::size_t size, std::size_t... sizes>
struct storage_type<_type, size, sizes...>
{
using type = std::array<typename storage_type<_type, sizes...>::type, size>;
};
template <typename _type>
struct storage_type<_type>
{
using type = _type;
};
I am now trying to implement the .at() function:
[[nodiscard]]
constexpr reference at (const size_type& position)
{
// This has to be:
// data_[position[0]][position[1]][position[2]]...;
}
Fold expressions do not work in this case so a recursive solution is necessary.
I think this is the way, but can't seem to come up with the right answer:
[[nodiscard]]
constexpr reference at(const size_type& position)
{
return access_type<value_type, sizeof...(sizes)>::at(data_, position);
}
template <typename type, std::size_t size, std::size_t index = 0>
struct access_type
{
template <typename array_type>
auto at (const array_type& array, const std::array<std::size_t, size>& position, type& current) // Problem: Reference is not a type& for intermediates.
{
if constexpr (index == 0)
current = &array;
if constexpr (index + 1 != size)
{
return access_type::at<type, size, index + 1>(array, position, current);
}
}
};
| Something along these lines, perhaps:
template <size_t level, size_t max_level>
struct Access {
template<typename Store>
static reference At(Store& store, const size_type& position) {
return Access<level + 1, max_level>::At(
store[position[level]], position);
}
};
template <size_t level>
struct Access<level, level> {
template<typename Store>
static reference At(Store& store, const size_type&) {
return store;
}
};
reference at(const size_type& position)
{
return Access<0, sizeof...(sizes)>::At(data_, position);
}
|
70,320,941 | 70,322,279 | Can I use classic Borland & clang compiler for the same application | I'm looking for some advice on how to migrate a C++Builder 5 project to Embarcadero C++Builder 11.
Some of the DLLs can only be compiled with the 'classic' Borland compiler. The rest can be compile with the Clang-compiler.
Can I use 2 different compilers in the same application?
|
I'm looking for some advice on how to migrate a C++Builder 5 project to Embarcadero C++Builder 11.
That is a very massive upgrade. A LOT has changed over the decades between the two versions. I hope you are reading the docs in Embarcadero's Migration and Upgrade Center, for starters.
Some of the DLLs can only be compiled with the 'classic' Borland compiler. The rest can be compile with the Clang-compiler.
Can I use 2 different compilers in the same application?
If the EXE and DLLs are all compiled to be self-contained (ie, no Runtime Packages, no Dynamic RTL, no shared Memory Manager, not sharing object files, etc), and they all follow safe guidelines about memory management and using only safe and compatible POD data types across the DLL boundaries, etc, then in that regard, it should be possible to compile each module with a different compiler.
|
70,321,047 | 70,343,177 | How CRC16 using bytes data is woking ? (for CAN bus implementation) | I have some trouble implementing a CRC16 for can message, I followed the instructions given by this website https://barrgroup.com/embedded-systems/how-to/crc-calculation-c-code and http://www.sunshine2k.de/articles/coding/crc/understanding_crc.html#ch5, plus other implention I have seen in here ( for example Function to Calculate a CRC16 Checksum).
I don't understand how it is processed.
My message here is in form of bytes, for example char message[4] = {0x12, 0x34, 0x56, 0x78}. When I go through the first loop I just take the first byte, shift it by 8 and calculate the remainder with a POLYNOME of 16 bits.
That means we have 0x1200 and we go through the second loop with it, which mean I do a XOR with the POLYNOME that I store in the remainder but I don't quite understand why this works, especially when I look at this code, the 2nd, 3rd and 4th bytesof my message which should get XORed by the 8 first bits of the POLYNOME at some points aren't going through it at all.
According to the wikipedia explanation https://en.wikipedia.org/wiki/Cyclic_redundancy_check the polynome goes through the whole message at once and not byte by byte.
I don't know how that translates to doing the CRC of 0x12345678 byte by byte.
uint16_t Compute_CRC16_Simple(char* message, int nbOfBytes)
{
uint16_t POLYNOME = 0xC599;
uint16_t remainder = 0;
for (int byte = 0;byte < nbOfBytes; byte++)
{
remainder ^= (message[byte] << 8);
for (int i = 0; i < 8; i++)
{
if (remainder & 0x8000)
{
remainder = (remainder << 1) ^ POLYNOME ;
}
else
{
remainder <<= 1;
}
}
}
return remainder;
}
|
I don't understand how it is processed.
Maybe it will help to describe the bit by bit operations for 8 bits of data:
crc[bit15] ^= data[bit7]
if(crc[bit15] == 1) crc = (crc << 1) ^ poly
else crc = crc << 1
crc[bit15] ^= data[bit6]
if(crc[bit15] == 1) crc = (crc << 1) ^ poly
else crc = crc << 1
...
crc[bit15] ^= data[bit0]
if(crc[bit15] == 1) crc = (crc << 1) ^ poly
else crc = crc << 1
Note that the if statement only depends on the bit value in crc[bit15], so the fixed part of the XOR with data could be done in one step:
crc[bit15 .. bit8] ^= data[bit7 .. bit0]
if(crc[bit15] == 1) crc = (crc << 1) ^ poly
else crc = crc << 1
if(crc[bit15] == 1) crc = (crc << 1) ^ poly
else crc = crc << 1
...
if(crc[bit15] == 1) crc = (crc << 1) ^ poly
else crc = crc << 1
The cycling of the CRC 8 times using those if ... then (shift + xor poly) else (just shift) could be precomputed for all 256 possible values in crc[bit15 .. bit8], and stored in a table for table lookup to cycle the CRC 8 times.
|
70,322,230 | 70,322,382 | Why does extern template instantiation not work on move-only types? | The following code is ok:
#include <memory>
#include <vector>
extern template class std::vector<int>;
template class std::vector<int>; // ok on copyable types
int main()
{
[[maybe_unused]] auto v1 = std::vector<int>{}; // ok
[[maybe_unused]] auto v2 = std::vector<std::unique_ptr<int>>{}; // ok
}
However, below is failed to compile:
#include <memory>
#include <vector>
extern template class std::vector<std::unique_ptr<int>>;
template class std::vector<std::unique_ptr<int>>; // error on move-only types
int main()
{
[[maybe_unused]] auto v1 = std::vector<int>{};
[[maybe_unused]] auto v2 = std::vector<std::unique_ptr<int>>{};
}
See: https://godbolt.org/z/8qe94oGx5
Why does extern template instantiation not work on move-only types?
| Explicit instantiation definition (aka template class ...) will instantiate all member functions (that are not templated themselves).
Among other things, it will try to instantiate the copy constructor for the vector (and other functions requiring copyability), and will fail at it for obvious reasons.
It could be prevented with requires, but std::vector doesn't use it. Interestingly, Clang ignores requires in this case, so I reported a bug.
|
70,322,262 | 70,322,483 | Why is "insert" of unordered_set Undefine Behavior here? | I am sorry for my fuzzy title.
Suppose there are some pointers of nodes, and I want to collect the nodes' pointers with unique value.
struct node_t
{
int value;
node_t(int v = -1) : value(v) {}
};
For example, if we have 4 pointers:
p1 points to node(1)
p2 points to node(1)
p3 points to node(2)
p4 points to node(2)
then I want to collect {p1, p3} here.
And this is what my code wrote:
#include <iostream>
#include <unordered_set>
#include <algorithm>
using namespace std;
struct node_t
{
int value;
node_t(int v = -1) : value(v) {}
};
struct myequal
{
bool operator()(const node_t *p1, const node_t *p2) const
{
return p1->value == p2->value;
}
};
int main()
{
unordered_set<node_t *, hash<node_t *>, myequal> table;
node_t n1(0), n2(0);
table.insert(&n1), table.insert(&n2);
cout << (&n1) << '\n';
cout << (&n2) << '\n';
cout << table.size() << '\n';
cout << *table.begin() << '\n';
}
I run the code on MacOS12, compile it with clang++ -std=c++17 xxx.cpp, but its output is unsure.
Sometimes it outputs:
0x7ff7bad974e0
0x7ff7bad974d0
1
0x7ff7bad974e0
But sometimes it outputs:
0x7ff7b4bdc4e0
0x7ff7b4bdc4d0
2
0x7ff7b4bdc4d0
Why do this happen?
According to the document of unordered_set,
Each element is inserted only if it is not equivalent to any other element already in the container (elements in an unordered_set have unique values).
| The short version is that your hash and equality operations are incompatible. When you insert an element, first the hash is taken, then the bucket for that hash is checked to see if an equivalent element is present.
Let's say there are three buckets named A, B, and C. You insert n1 and it ends up in, let's say, bucket B. Next you insert n2.
If n2 gets hashed to bucket B, then the equivalent n1 is found in that bucket, so n2 is not inserted.
If n2 gets hashed to bucket A (or C), then that bucket – and only that bucket – is checked to see if the element already exists. Bucket A is empty, so of course no equivalent element is found. So n2 is inserted.
To make your hash and equality operations compatible, equal things must compute to the same hash. That ensures that equal things will be assigned to the same bucket (ensures that n2 gets hashed to bucket B in the above example). If equality is based upon p1->value, then the hash better be based upon p1->value.
Documentation from cppreference.com:
If two Keys are equal according to Pred, Hash must return the same value for both keys.
|
70,322,288 | 70,322,409 | Reverse iterators and negative strided iterators in C++, using one before beginning as sentinel | In Another way of looking at C++ reverse iterators Raymond Chen wrote:
... a quirk of the C++ language: You are allowed to have a pointer
"one past the end" of a collection, but you are not allowed to have a
pointer "one before the beginning" of a collection.
I understand that it probably means "undefined behavior" and that is pretty much a conversation ender. But I am curious what is the worst that can happen in a realistic system if one ignores this rule. A segmentation fault? an overflow of pointer arithmetic? unnecessary paginations?
Remember that the pointer "before" the beginning (like "end") is not supposed to be referenced either, the problem seem to have the pointer just trying to point to it.
The only situation I can imagine it can be a problem is with a system where memory location "0" is valid.
But even then, if that is so there are bigger problems, (e.g. nullptr would be problematic in itself too and wrapping around might still work by convention I guess.)
I am not questioning the implementation of reverse_iterator with an off-by-one special code.
The question occurred to me because if you have a generic implementation of "strided" iterator would require a special logic for negative strides and that has a cost (in code and at runtime).
Arbitrary strides, including negative ones could be naturally appearing with multidimensional arrays.
I have a multidimensional array library in which I always allowed negative strides in principle, but now I realized that they should have a special code (different from the positive case) if I allowed them at all and I don't want to expose undefined behavior.
|
But I am curious what is the worst that can happen in a realistic
system if one ignores this rule. A segmentation fault? an overflow of
pointer arithmetic? unnecessary paginations?
Wasted space.
To be able to form the address "one before" you need to have the space available. For example, if you have a 1k struct, it must start at least 1k from the beginning of memory. On a small device with limited memory, or an x86 with segmented memory, that can be tricky.
To form a "one past" pointer/iterator you only need one byte beyond the end. As it cannot be dereferenced anyway, there is no need to have space for an entire object, just the possibility to form the address.
From the comments:
At the time the rules were defined, we had real CPUs with dedicated address registers that validated the address against the segment size on register load. That made sure that a -1 address would trap...
https://en.wikipedia.org/wiki/Motorola_68000#Architecture
This ruled out the case of having "one before" wrapping around to the end of the segment. Because if the segment is small, the resulting end might not be there.
|
70,322,507 | 70,345,640 | Why LLVM's leak sanitizer not working when using with other sanitizers enabled | I was trying to find a memory leak from a simple program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
void parse(const char* input) {
// Goal: parse out a string between brackets
// (e.g. " [target string]" -> "target string")
char *mutable_copy = strdup(input);
// Find open bracket
char *open_bracket = strchr(mutable_copy, '[');
if (open_bracket == NULL) {
printf("Malformed input!\n");
free(mutable_copy);
return;
}
// Make the output string start after the open bracket
char *parsed = open_bracket + 1;
// Make sure there is at least one character in brackets
if (parsed[0] == '\0') {
printf("There should be at least one character in brackets!\n");
free(mutable_copy);
return;
}
// Find the close bracket
char *close_bracket = strchr(parsed, ']');
if (close_bracket == NULL) {
printf("Malformed input!\n");
return;
}
// Replace the close bracket with a null terminator to end the parsed
// string there
*close_bracket = '\0';
printf("Parsed string: %s\n", parsed);
free(mutable_copy);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <string to parse>\n", argv[0]);
return 1;
}
parse(argv[1]);
return 0;
}
with the following command:
clang -g -O0 -Wall -Wextra -std=gnu99 -fsanitize=address,leak -o 3-bracket-parser 3-bracket-parser.c
It's obvious that in this program, if close_bracket == NULL is true, then the program returns without free mutable_copy, so there is a memory leak.
However, when I run this command, it reports no error and there is no output from my sanitizers. I tried again with only leak sanitizer enabled, and this time it works:
=================================================================
==19699==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 17 byte(s) in 1 object(s) allocated from:
#0 0x10f77ab48 in wrap_malloc+0x58 (libclang_rt.lsan_osx_dynamic.dylib:x86_64h+0x9b48)
#1 0x7fff202b88d1 in strdup+0x1f (libsystem_c.dylib:x86_64+0x578d1)
#2 0x10f763db4 in parse 3-bracket-parser.c:10
#3 0x10f763edd in main 3-bracket-parser.c:51
#4 0x7fff203a7f3c in start+0x0 (libdyld.dylib:x86_64+0x15f3c)
SUMMARY: LeakSanitizer: 17 byte(s) leaked in 1 allocation(s).
I was wondering why leak sanitizer isn't working when other sanitizers are enabled.
My clang version is Homebrew clang version 12.0.1, and my OS is macOS Big Sur 11.5.2
| Problem solved. It turns out that on OS X, lsan is integrated into asan, and one must manually use ASAN_OPTIONS=detect_leak=1 to enable lsan when using asan. It seems that if one uses -fsanitize=address,leak, clang thinks that this leak parameter is redundant since address sanitizer already includes leak sanitizer. If you look closely to the linking command, you may find out that ld only links asan dylib when both sanitizers are enabled, and you need to add ASAN_OPTIONS to enable lsan. However, if you use leak sanitizer standalone, so there is no need to use ASAN_OPTIONS to specify you want lsan enabled as well, and lsan works fine this way.
|
70,322,930 | 70,322,991 | How to pass a constexpr as a function parameter c++ | I have a simple function that populates an array with double values and returns the array:
double create_step_vectors(int n_steps, double step_size)
{
std::array<double, n_steps + 1> vec{};
for (int i = 0; i <= n_steps; i++)
{
arr[i] = i * step_size;
}
return arr
}
I pass in n_steps which is defined in main scope as:
constexpr int n_step {static_cast<int>(1 / x_step) };
I get the error:
error: 'n_steps' is not a constant expression
13 | std::array<double, n_steps + 1> vec{};
I have tried to put n_steps + 1 in curly brackets which didn't help. The purpose of n_steps, where the error occurs, is to set the size of the array, arr.
How could I solve this issue?
| You cannot use a function parameter where a compile-expression is expected, because the parameter is not constexpr, even in constexpr function (your constexpr function could also be called with non-constexpr values).
In your case, the easiest solution is probably to use a non-type template parameter:
template <int n_steps>
auto create_step_vectors(double step_size)
{
std::array<double, n_steps + 1> arr;
for (int i = 0; i <= n_steps; i++)
{
arr[i] = i * step_size;
}
return arr;
}
And then
constexpr int n_step{ static_cast<int>(1 / x_step) };
const auto arr = create_step_vectors<n_step>(1.);
|
70,323,234 | 70,323,270 | make a counter in c++ which calculate the number of steps | I make a program which require from the user to enter a number then make this number reach 1 by doing a loop if the number reach an odd value the program will multiply it by 3 then add 1 to it
if the number reach an even value the program will divide it by 2 ... until reachig 1 .so i make a counter to count the number of steps but it output wrong value . this is my code:
#include<iostream>
using namespace std;
int main()
{
unsigned int x;
int counter ;
cout<<"enter a number:"<<endl;
cin>>x;
while (x!=1) {
if (x%2!=0) {
counter++;
x=3*x+1;
cout<<x<<endl;
}
else if (x%2==0) {
counter++;
x=x/2;
cout<<x<<endl;
}
else {
counter++;
cout<<x<<endl;
}
}
cout<<"the value of the counter is :"<<counter;
}
| You haven’t init counter variable so it can contain any number. Set it to zero when declare:
int counter = 0;
|
70,323,434 | 70,323,482 | C++11 about *begin(a) | #include<iterator>
#include<iostream>
int a[5][4];
int main()
{
cout << *begin(a);
}
Why does this cout print the same as begin(a)?
It seems the * does not dereference the pointer returned by begin(a)?
Can anyone tell me why?
| Here * affects only the type of the pointer, and not its numerical value.
std::begin(a) returns a pointer to the first element of a, of type int (*)[4] (pointer to an array of 4 ints).
*std::begin(a) returns int[4]. Since cout can't print arrays directly, the array then decays to the pointer to its first element, of type int *, and is printed as such.
**std::begin(a) would return an int.
|
70,323,837 | 70,323,871 | How to use the global comparison operator when comparing two different structure types to resolve the errors in C++ | When I am trying to compare members of two different structures, getting the below errors:
error C2676: binary '==': 'main::strRGBSettings' does not define this operator or a conversion to a type acceptable to the predefined operator
error C2678: binary '==': no operator found which takes a left-hand operand of type 'const T1' (or there is no acceptable conversion)
Can someone help how to use the global comparison operator
#include <string>
#include <iostream>
int main()
{
struct strRGBSettings
{
uint8_t red;
uint8_t green;
uint8_t blue;
};
struct strStandardColors
{
static strRGBSettings black() { return { 0x00, 0x00, 0x00 }; }
static strRGBSettings red() { return { 0xFF, 0x00, 0x00 }; }
static strRGBSettings blue() { return { 0x00, 0x00, 0xFF }; }
};
struct ColorState
{
strRGBSettings RGB;
};
ColorState l_colorState;
if (l_colorState.RGB == strStandardColors::red())
{
std::cout << "The color is of type Red " << std::endl;
}
return 0;
}
Thank you
| As the compiler error says, you need to define operator== for your strRGBSettings struct:
struct strRGBSettings {
uint8_t red;
uint8_t green;
uint8_t blue;
bool operator==(const strRGBSettings& stg) const {
return stg.red == red && stg.blue == blue && stg.green == green;
}
};
If you cannot modify the struct, define operator== as a non-member function:
bool operator==(const strRGBSettings& stg1, const strRGBSettings& stg2) const {
return (stg1.red == stg2.red && stg1.blue == stg2.blue && stg1.green == stg2.green);
}
Note that this definition cannot go inside main, and you should at least be able to access the struct outside main.
|
70,324,040 | 70,325,075 | how to distinguish between no time and midnight in COleDateTime class | We use the DD-MM-YYYY HH:mm:ss date and time format API between frontend and backend.
However, there are cases that backend gets only the date since time wasn’t selected at the frontend side.
The GET call parameter will look like this:
startTime=16-11-2021
At the backend side, we use the COleDateTime class in order to parse the date and time. The problem is that the time in the case above is initialized to 00:00:00 when actually no time is sent. I need a way to distinguish between no time sent and midnight as the actual time is significant in our system and there is a big difference between no time sent and midnight.
It seems that the ParseDateTime function expects to get a flag in its second parameter VAR_TIMEVALUEONLY to Ignore the date portion during parsing.
So for that, I need to implement a parse function in order to know if I got the time or not where it is expected that the ParseDateTime function would be set as an undefined time like -1 when no time is sent.
Is there a way to distinguish between no time to midnight in COleDateTime class? If not, maybe you have another way I can use public libraries like <chrono> which could solve my problem?
| COleDateTime has a function GetStatus() that is able to tell if the object has no value at all. In all other cases, it's valid. This means that there is no distinction between "no time" and midnight. The type seems designed to encode an absolute point in time. Date-only or time-only hijack this encoding with 0 components. No-date can easily be spotted, since numbering of date start at 0100-01-01 and cannot be confused with 0000-00-00. Nothing supports the spotting of no-time.
If you need a better handling of time uncertainty, this format is not suitable as it is. Unfortunately, most other common alternatives have similar issues. <chrono> would offer an equivalent feature which is the time_point. It also supports dates and time of day separately, with lots of conversion. Boost has similar limitations, as does DateTime (unless you'd misuse the milliseconds, which would look weird).
As you get the time from the front end in DD-MM-YYYY HH:mm:ss or DD-MM-YYYY format, it's pretty easy for you to parse if there is or not time. The simplest would probably to create a DateTimeWrapper to wrap COleDateTime together with isTimeAccurate indicator.
|
70,324,047 | 70,325,794 | How to convert winrt::hstring to int in C++ Winui application? | I have used the template called Blank App, Package (Winui 3 in desktop) inside Visual Studio. I want to make a really simple function which add 2 value together. This is what the application looks like.
This is the XAML code:
<StackPanel>
<TextBox x:Name="Box1" PlaceholderText="First number"></TextBox>
<TextBox x:Name="Box2" PlaceholderText="Second number"></TextBox>
<Button x:Name="myButton" Click="myButton_Click">Calculate</Button>
<TextBlock x:Name="answer"></TextBlock>
</StackPanel>
This is the code in C#.
private void myButton_Click(object sender, RoutedEventArgs e)
{
int number1 = Convert.ToInt32(Box1.Text);
int number2 = Convert.ToInt32(Box2.Text);
int sum = number1 + number2;
answer.Text = sum.ToString();
}
Everything is good in C# but when I moved to C++. I got some type error which winrt::hstring cannot be convert to int. Below is the C++ code
This code got problem
void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&)
{
int number1 = stoi(Box1().Text());
int number2 = stoi(Box2().Text());
int sum = number1 + number2;
answer().Text(L"");
}
| I found a method.
std::string number_1 = winrt::to_string(Box1().Text());
std::string number_2 = winrt::to_string(Box2().Text());
int number1 = stoi(number_1);
int number2 = stoi(number_2);
int sum = number1 + number2;
winrt::hstring h_string_sum = winrt::to_hstring(sum);
answer().Text(h_string_sum);
|
70,324,055 | 70,325,835 | Is there any workaround for passing a function template as a template parameter? | I'm trying to make a function template that takes a function template as a template argument and then returns the result of that function when invoked with the normal function parameters passed in. It would be used like this:
auto fooPtr = func<std::make_unique, Foo>(...);
The point of the function is to allow template type deduction even when letting another function perform construction of an instance. I already do this manually in a lot of places in my code like this:
auto fooPtr = std::make_unique<decltype(Foo{...})>(...);
I got the idea of a helper function from this answer to a question I posted. He suggested to make one for a specific type but I want a function that can be used for any type.
Here's what I've come up with so far:
template
<auto F, template<typename U> class T, typename... Args>
std::result_of_t<decltype(F)>
func(Args&&... args, std::enable_if_t<std::is_invocable_v<decltype(F), Args...>>* = nullptr)
{
return F<decltype(T{std::forward<Args>(args)...})>(std::forward<Args>(args)...);
}
But I can't get it to work.
Am I on the right track? Is what I'm trying to do even possible?
| You can't pass a templated function as a template argument unfortunately unless you specify the template arguments explicitly, e.g.:
template<auto T>
auto func(auto&&... args) {
return T(std::forward<decltype(args)>(args)...);
}
struct Foo { Foo(int i) {} };
int main() {
auto unique_foo = func<std::make_unique<Foo, int>>(1);
}
You can however pass around templated function objects without problems, so the following would work:
template<class T>
struct unique {
auto operator()(auto&&... args) {
return std::make_unique<T>(std::forward<decltype(args)>(args)...);
}
};
template<class T>
struct shared {
auto operator()(auto&&... args) {
return std::make_shared<T>(std::forward<decltype(args)>(args)...);
}
};
template<template<class> class F, class T, class... Args>
requires std::is_invocable_v<F<T>, Args...>
auto func(Args&&... args) {
return F<T>{}(std::forward<Args>(args)...);
}
struct Foo { Foo(int i) {} };
int main(){
auto foo_unique = func<unique, Foo>(1);
auto foo_shared = func<shared, Foo>(2);
}
godbolt example
If you also need to deduce the template parameters of your class by the parameters passed to std::make_unique (like in your linked example), you can add an overload for func that deals with templated types:
template<template<class...> class T, class... Args>
using deduced_type = decltype(T{std::declval<Args>()...});
template<template<class> class F, template<class...> class T, class... Args>
requires std::is_invocable_v<F<deduced_type<T,Args...>>, Args...>
auto func(Args&&... args) {
return F<deduced_type<T, Args...>>{}(std::forward<Args>(args)...);
}
godbolt example
that deduces the template parameters to your type T based on the passed in parameters.
template<class A, class B>
struct Foo { Foo(A,B) {} };
struct Bar { Bar(int i) {} };
int main(){
// automatically deduces the types for A, B in Foo based on arguments
auto foo_unique = func<unique, Foo>(1, 2);
// the normal overload of func handles non-templated classes:
auto bar_unique = func<unique, Bar>(1);
}
|
70,324,119 | 70,324,296 | Why is assigning an int to enum type valid in OpenCV _InputArray::kind()? | I think assigning and int value to an enum variable is invalid in C++, and there's already questions verifying this, such as cannot initialize a variable of type 'designFlags' with an rvalue of type 'int' .
However I just see the following code not causing compile error:
// https://github.com/opencv/opencv/blob/4.x/modules/core/include/opencv2/core/mat.hpp#L158-L265
class CV_EXPORTS _InputArray
{
public:
enum KindFlag { //!! KindFlag is an enum type
KIND_SHIFT = 16,
FIXED_TYPE = 0x8000 << KIND_SHIFT,
FIXED_SIZE = 0x4000 << KIND_SHIFT,
KIND_MASK = 31 << KIND_SHIFT,
...
}
...
};
// https://github.com/opencv/opencv/blob/4.x/modules/core/src/matrix_wrap.cpp#L370-L378
_InputArray::KindFlag _InputArray::kind() const
{
KindFlag k = flags & KIND_MASK; //!! this line, I think it is assign enum type var `k` with int value `flag & KIND_MASK`, but it it not cause compile error
#if CV_VERSION_MAJOR < 5
CV_DbgAssert(k != EXPR);
CV_DbgAssert(k != STD_ARRAY);
#endif
return k;
}
I try to implement a minimal InputArray_ class with the following, which will cause compile error, with the same assigne as above, which make me confused:
// what.cpp
class InputArray_
{
public:
enum KindFlag {
KIND_SHIFT = 16,
KIND_MASK = 31 << KIND_SHIFT,
NONE = 0 << KIND_SHIFT,
MAT = 1 << KIND_SHIFT
};
bool empty() const;
InputArray_::KindFlag kind() const;
public:
InputArray_();
protected:
int flags;
void* obj;
};
InputArray_::KindFlag InputArray_::kind() const
{
KindFlag k = flags & KIND_MASK; //!! now this cause compile error
return k;
}
int main()
{
}
The compiler is AppleClang 13.0.0, the full error message is:
what.cpp:26:14: error: cannot initialize a variable of type 'InputArray_::KindFlag' with an rvalue of type 'int'
KindFlag k = flags & KIND_MASK;
^ ~~~~~~~~~~~~~~~~~
1 error generated.
Does anyone know why OpenCV's one won't cause compile error?
| opencv define the operator & itself so it no more result in int
you can see it just below the section you linked
__CV_ENUM_FLAGS_BITWISE_AND(_InputArray::KindFlag, int, _InputArray::KindFlag)
link
Implementation of the macro
#define __CV_ENUM_FLAGS_BITWISE_AND(EnumType, Arg1Type, Arg2Type) \
static inline EnumType operator&(const Arg1Type& a, const Arg2Type& b) \
{ \
typedef std::underlying_type<EnumType>::type UnderlyingType; \
return static_cast<EnumType>(static_cast<UnderlyingType>(a) & static_cast<UnderlyingType>(b)); \
}
link
|
70,324,402 | 70,324,492 | Why is the output different even though the expressions are the same in lambda expression? | I have problem about lambda expression like this:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int sum(vector<int>& v){
int total = 0;
auto lambda = for_each(v.begin(), v.end(), [&total](int n){total += n;});
lambda; // lambda expression doesn't work.
for_each(v.begin(), v.end(), [&total](int n){total += n;}); // work same as I intended.
return total;
}
int main(void){
vector<int> v = {1, 2, 3, 4, 5};
cout << sum(v) << endl; // 30 (I think this should be 45.)
}
I thought that lambda; could do same things like for_each algorithm. Why lambda; doesn't works?
| according to cppreference, the for_each(...) call returns the UnaryFunction which was passed to the function.
In this case, the for_each returns the UnaryFunction
[&total](int n){total += n;}
a lambda(5) would increase the total value by 5.
A solution would be to put the for_each call in a separate function - which is actually a "sum" function.
This is already done by the std:accumulate function
std::accumulate(v.begin(), v.end(), 0);
|
70,324,964 | 70,325,133 | Question about using string arrays as function parameters | I am a novice, I encountered a little problem today, I hope to get someone's answer, thank you very much.
Code show as below。
#include<iostream>
using namespace std;
void sub(char b[]){
b[] = "world"; //I alse try b*/b,but it is not ok
}
int main(void){
char a[10] = "hello";
sub(a);
cout<<a<<endl;
system("pause");
return 0;
}
error: expected primary-expression before ']' token
b[] = "world";
^
The error
I want the final output will be "world". The function sub() can run correctly. What should I do?
| strcpy(b, "world"); // need <string.h>
But I would use std::string (instead of c-string) directly.
#include<iostream>
#include<string>
using std::cout;
using std::string;
void sub(string &b){
b = "world";
}
int main(){
string a = "hello";
sub(a);
cout << a << endl; // output
system("pause");
return 0;
}
|
70,325,557 | 70,326,295 | How do i make a piezo play 3 times and then stopping in Arduino? | EDIT: https://www.tinkercad.com/things/ampvgOj75D1
This is the link to my tinkercad project witch contains the wiring of the circuit, sorry that i forgot it's also needed to get the code working.
I need this code to make the piezo play 3 times and then stopping it completely, the while() loop does not work for some reason.
I tried moving around the i++ function but it does not work. If i state i=0; globally the piezo never plays, if i put it in loop() it keeps repeating without stopping the third time.
int i=0;
const byte speakerPin=9;
unsigned long CurrentMillis;
unsigned long lastPeriodStart;
const int onDuration=100;
const int periodDuration=500;
void setup()
{
pinMode(9, OUTPUT);
Serial.begin(9600);
}
void loop()
{
CurrentMillis = millis();
Serial.println(i);
while(i<=3)
{
if (CurrentMillis-lastPeriodStart>=periodDuration)
{
lastPeriodStart = millis();
tone(speakerPin,550, onDuration);
}
i++;
}
}
| Your actual code not work due to variable i is incremented in every loop. So this mean i is more then 3 in very short time and if statement is still false.
If you move i++ statement inside if, your code not leave while loop, because CurrentMillis is not updated.
My recomendation:
use Serial.println("message"); to trace your code, in all branches your code
move i++; statement inside if
replace while statement by if
|
70,325,993 | 70,326,049 | Casting weak_ptr<IBase> to weak_ptr<Derived> | I am trying to create object pooling with an interface base using smart pointers. However I cannot access the derived object without casting it from a weak_ptr to a raw pointer, which kind of kills the purpose of smart pointers. Also it warns me it is vulnerable to the dangling pointer state.
Yes the code compiles, but I don't like warnings and at the moment it shouldn't be 100% safe regardless.
std::weak_ptr<IPooledObject> weakPtr = poolManager.SpawnFromPool();
if (EnemyEntity* enemy0 = reinterpret_cast<EnemyEntity*>(weakPtr.lock().get()))
C26815: The pointer is dangling because it points at a temporary instance which was destroyed.
Now what I actually want instead is to cast the weak_ptr with IPooledObject returned from poolManager.SpawnFromPool() into another weak_ptr with the derived class EnemyEntity instead.
std::weak_ptr<EnemyEntity> enemy0 = poolManager.SpawnFromPool();
The last code snippet is how I ideally want to use it, but it doesn't compile. I can't figure out the correct syntax myself how to cast between the two weak pointer types (from IBase to Derived). Could anyone help?
| To avoid the dangling pointer issue you need to ensure that a shared_ptr will be alive for the entire time you need access to the object. Then, use dynamic_pointer_cast to execute a dynamic_cast on the pointee:
if (auto sharedPtr = weakPtr.lock()) {
std::weak_ptr enemy0 = std::dynamic_pointer_cast<EnemyEntity>(sharedPtr);
} else {
// weakPtr has expired
}
|
70,326,228 | 70,326,344 | Output buffer empty in iconv , while converting from ISO-8859-1 to UTF-8 | In linux I have created a file with Turkish characters and changed file characterset to "ISO-8859-9". With below cpp, I am trying to convert it to UTF-8. But iconv returns empty outbuffer. But "iconv" returns "inbytesleft" as "0" means conversion done on input. What could be the mistake here?
My linux file format:
[root@osst212 cod]# file test.txt
test.txt: ISO-8859 text
[root@osst212 cod]# cat test.txt --> Here my putty Characterset setting is ISO-8859-9
fıstıkçı şahap
#include <string>
#include <iostream>
#include <locale>
#include <cstdlib>
#include <fstream>
#include <string>
#include <sstream>
#include <iconv.h>
#include <cstring>
#include <cerrno>
#include <csignal>
using namespace std;
int main()
{
const char* lna = getenv("LANG");
cout << "LANG is " << lna << endl;
setlocale(LC_ALL, "tr_TR.ISO8859-9");
ifstream fsl("test.txt",ios::in);
string myString;
if ( fsl.is_open() ) {
getline(fsl,myString); }
size_t ret;
size_t inby = sizeof(myString); /*inbytesleft for iconv */
size_t outby = 2 * inby; /*outbytesleft for iconv*/
char* input = new char [myString.length()+1]; /* input buffer to be translated to UTF-8 */
strcpy(input,myString.c_str());
char* output = (char*) calloc(outby,sizeof(char)); /* output buffer */
iconv_t iconvcr = iconv_open("UTF-8", "ISO−8859-9");
if ((ret = iconv(iconvcr,&input,&inby,&output,&outby)) == (size_t) -1) {
fprintf(stderr,"Could not convert to UTF-8 and error detail is \n",strerror(errno)); }
cout << output << endl;
raise(SIGINT);
iconv_close(iconvcr);
}
Local variables after iconv called are as below, when I run it under gdb. You can see output is empty.
(gdb) bt
#0 0x00007ffff7224387 in raise () from /lib64/libc.so.6
#1 0x0000000000401155 in main () at stack.cpp:41
(gdb) frame 1
#1 0x0000000000401155 in main () at stack.cpp:41
41 raise(SIGINT);
(gdb) info locals
lna = 0x7fffffffef72 "en_US.UTF-8"
fsl = <incomplete type>
ret = 0
inby = 0
outby = 4
myString = "f\375st\375k\347\375 \376ahap"
input = 0x606268 " \376ahap"
output = 0x60628c ""
iconvcr = 0x606a00
| man 3 iconv
The iconv() function converts one multibyte character at a time, and for each character conversion it increments *inbuf and decrements *inbytesleft by the number of converted input bytes, it increments *outbuf and decrements *outbytesleft by the number of converted output bytes.
output is updated to point next not used byte in the originally allocated buffer.
The proper usage
char* nextouput = output:
if ((ret = iconv(iconvcr, &input, &inby, &nextoutput, &outby)) == (size_t) -1) {
fprintf(stderr, "Could not convert to UTF-8 and error detail is \n", strerror(errno)); }
|
70,326,638 | 70,326,816 | Opencv, can't get destroyAllWindows to work | OpenCV 4.5.4, C++ and Win10.
Probably my syntax doesn't compute with this, but can anyone spot a fix to my problem? I can get the usb webcam window to open and it shows the stream. But I cannot close it.
This opens the window but brings no image in stream at all:
cv::imshow("Smaller", resized_down);
int c = cv::waitKey(1);
if ((char)c == 'c')
cv::destroyAllWindows();
break;
This works better, it shows the image stream, but by pressing C, it only freezes the image:
cv::imshow("Smaller", resized_down);
int c = cv::waitKey(1);
if ((char)c == 'c')
break;
Please, indicate if you need to see more of my code.
| your first code should work with this fix (break; is always executing in your code!):
cv::namedWindow(“Smaller”);
while(true){
…
cv::imshow("Smaller", resized_down);
int c = cv::waitKey(1);
if ((char)c == 'c'){
cv::destroyAllWindows();
break;
}
…
}
|
70,326,861 | 70,328,042 | C++ CUDA: Why aren't my block dimensions working? | I'm using an example from a book to solve a 4x4 matrix multiplication. However, the book only provides the kernel code, so the rest of the program is down to me. The book says to use a block width of 2, however I cannot get this to work with dim3 variables. Here is the kernel:
__global__ void matmul_basic(float *c, float *a, float *b, unsigned int width)
{
printf("Width: %d\n", width);
printf("BlockDim.x: %d, BlockDim.y: %d, BlockDim.z: %d\n", blockDim.x, blockDim.y, blockDim.z);
printf("GridkDim.x: %d, GridDim.y: %d, GridDim.z: %d\n", gridDim.x, gridDim.y, gridDim.z);
printf("Blockidx.x: %d, Blockidx.y: %d, Blockidx.z: %d\n", blockIdx.x, blockIdx.y, blockIdx.z);
printf("threadIdx.x %d, threadIdx.y: %d, threadIdx.z: %d\n", threadIdx.x, threadIdx.y, threadIdx.z);
// Calculate the row index of the c element and a
int Row = blockIdx.y * blockDim.y + threadIdx.y;
// Calculate the column index of c and b
int Col = blockIdx.x * blockDim.x + threadIdx.x;
// Sense check
printf("Row: %d\tCol: %d\n", Row, Col);
if ((Row < width) && (Col < width)) {
float Pvalue = 0;
// each thread computes one element of the block sub-matrix
for (size_t k = 0; k < width; k++)
{
Pvalue += a[Row * width + k] * b[k * width + Col];
}
c[Row * width + Col] = Pvalue;
}
else {
printf("Dimensions out of bounds. Row: %d, Col: %d\n", Row, Col);
}
}
I know the print statements are excessive, but I'm just trying to verify the dimensions. Here are the dimensions in the function call:
dim3 dimGrid = (1, 1, 1);
dim3 dimBlock = (2, 2, 1);
matmul_basic <<<dimGrid, dimBlock>>> (d_c, d_a, d_b, width);
This should be a single block of dimension 2x2 threads?
And finally, here is the readout:
Width: 4
BlockDim.x: 1, BlockDim.y: 1, BlockDim.z: 1
GridkDim.x: 1, GridDim.y: 1, GridDim.z: 1
Blockidx.x: 0, Blockidx.y: 0, Blockidx.z: 0
threadIdx.x 0, threadIdx.y: 0, threadIdx.z: 0
Row: 0 Col: 0
Kernel Complete, transferring results...
20218 -1.07374e+08 -1.07374e+08 -1.07374e+08
-1.07374e+08 -1.07374e+08 -1.07374e+08 -1.07374e+08
-1.07374e+08 -1.07374e+08 -1.07374e+08 -1.07374e+08
-1.07374e+08 -1.07374e+08 -1.07374e+08 -1.07374e+08
So it never goes past the very first thread, and it thinks the block size is 1x1x1? It also never goes to the else statement which would indicate it is outside the matrix dimensions.
I'm sure I'm doing something stupid or I'm misunderstanding how the dimensions work. Any help would be greatly appreciated. Thanks!
EDIT:
Adding width initialisation and readout from printf statement:
initialisation:
// Determine matrix dimensions
const int width = 4;
Readout in original section above has been edited to include width.
|
it thinks the block size is 1x1x1?
Yes.
Why aren't my block dimensions working?
Because this:
dim3 dimBlock = (2, 2, 1);
is not doing what you think it is doing, and it is not the proper way to initialize a dim3 variable. You might want to spend some time thinking about what the expression (2,2,1) evaluates to in C++. Underneath the hood, a dim3 variable is a struct with 3 components. You can't set all 3 components of a 3-element struct that way in C++.
Anyhow, you'll have better luck with something like this, which invokes a constructor to set the values:
dim3 dimBlock(2, 2, 1);
or this, which doesn't:
dim3 dimBlock;
dimBlock.x = 2;
dimBlock.y = 2;
dimBlock.z = 1;
I would also point out that for a 4x4 problem, your grid sizing is not correct either, but you will probably figure that out.
|
70,326,968 | 70,339,954 | Show tooltip at mouse position and show legend on top-right corner | The following toy problem show two tabs, each tab contains a QGridLayout, which has a ScrollArea on one of the cells, which in turn contains a customized QLabel (MyLabel). When the user moves his mouse on the customzied QLabel, a tooltip shows up for several seconds.
test.pro
QT += core gui widgets
CONFIG += c++17
CONFIG += debug
QMAKE_CXXFLAGS += -std=c++17
SOURCES += \
test.cpp
QMAKE_CLEAN += $$TARGET Makefile
HEADERS += \
mywidget.h
test.cpp
#include "mywidget.h"
#include <QApplication>
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyMainWindow myMainWindow;
myMainWindow.show();
return a.exec();
}
mywidget.h
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QDebug>
#include <QWidget>
#include <QMdiArea>
#include <QMainWindow>
#include <QScrollArea>
#include <QLabel>
#include <QGridLayout>
#include <QMouseEvent>
#include <QToolTip>
class MyLabel : public QLabel
{
Q_OBJECT
public:
MyLabel(QWidget *parent=nullptr, const QString &name="")
: QLabel(parent), m_name(name)
{
resize(1800, 1200);
setMouseTracking(true);
}
private:
void mouseMoveEvent(QMouseEvent *ev) override {
QToolTip::showText(
ev->globalPosition().toPoint()
, m_name + ": " + QString::number(ev->pos().x()) + ", " + QString::number(ev->pos().y())
);
QLabel::mouseMoveEvent(ev);
}
private:
QString m_name;
};
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(QWidget* parent = nullptr, const QString &name="")
: QWidget(parent), m_name(name)
{
setWindowTitle(name);
m_gridLayout = new QGridLayout(this);
this->setLayout(m_gridLayout);
// layout col 1
m_gridLayout->addWidget(new QLabel("smaller label", this), 0, 0);
// layout col 2
m_scrollArea = new QScrollArea(this);
MyLabel *label = new MyLabel(this, m_name);
m_scrollArea->setWidget(label);
m_gridLayout->addWidget(m_scrollArea, 0, 1);
}
private:
QString m_name;
QGridLayout *m_gridLayout;
QScrollArea *m_scrollArea;
};
class MyMainWindow : public QMainWindow
{
Q_OBJECT
public:
MyMainWindow(QWidget* parent = nullptr)
: QMainWindow(parent)
{
m_mdiArea = new QMdiArea(this);
this->setCentralWidget(m_mdiArea);
MyWidget *myWidget1 = new MyWidget(this, "widget 1");
m_mdiArea->addSubWindow(myWidget1);
MyWidget *myWidget2 = new MyWidget(this, "widget 2");
m_mdiArea->addSubWindow(myWidget2);
m_mdiArea->setViewMode(QMdiArea::ViewMode::TabbedView);
}
private:
QMdiArea *m_mdiArea;
};
#endif // MYWIDGET_H
Here are two problems that I am struggling with:
How can I show the tooltip without moving my mouse when I toggle between those two tabs by Ctrl+Tab? In my real-world problem, I use the tooltip show information about data at the mouse point.
Is it possible show some legends on the top-right corner of the viewport of the QScollArea, regardless of the positions of the scoll bars? I am trying with paintEvent, but had difficulties get the position adjusting according to scoll bars.
| Cursor postion can be retrieved by using QCursor::pos(), so both problems can be sovlved by using QCuros::pos() in paintEvent. I was confused by the fact paintEvent does not directly provide cursor position, as mouseMoveEvent does.
|
70,327,211 | 70,327,367 | selection sort using recursion | void swap(int a[], int x, int y)
{
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
void sort(int arr[], int x)
{
static int count = 0;
if (x == 1)
{
return;
}
int min = 100; // random value
int index;
for (int i = 0; i < x; i++)
{
if (arr[i] < min)
{
min = arr[i];
index = i;
}
}
swap(arr, count, index);
count++;
sort(arr + 1, x - 1);
}
int main()
{
int x;
cin >> x;
int A[x];
for (int i = 0; i < x; i++)
{
cin >> A[i];
}
sort(A, x);
for (int i = 0; i < x; i++)
{
cout << A[i] << " ";
}
cout << endl;
return 0;
}
this code is of selection sort using recursion. It is printing garbage values. what's the mistake in this. i am not sure but i guess because of using the static variable in the sort function(). it is printing garbage values
| Replace swap(arr, count, index); with
swap(arr, 0, index);
and remove static int count = 0;.
Replace sort(A, x); in the main with
sort(A, x - 1);
and change the condition if (x == 1) to if (x == 0).
I suggest to rename index to last.
Replace min = 100; with
min = arr[0];
|
70,327,567 | 70,327,659 | How to initialize a std::vector from variadic templates with different type each? | My main problem is that i'm trying to create a function that initialize a std::vector of a class that can be initialized by different ways, so I decided to use variadic templates, but, like in this example, that does not compile:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct MyClass {
MyClass(int v): value(v){}
MyClass(string v): value(stoi(v)){}
int value;
};
template<typename ...Args> vector<MyClass> mc_vector(const Args &...args);
int main()
{
auto vec = mc_vector(1, "3", 5);
for (auto &i : vec)
cout << i.value << " ";
cout << endl;
}
template<typename ...Args, typename T> void mc_vector_(vector<MyClass>& vec, const Args &...args, const T& t) {
vec.emplace_back(t);
mc_vector_(vec, args...);
}
template<typename ...Args> vector<MyClass> mc_vector(const Args &...args) {
vector<MyClass> vec;
vec.reserve(sizeof...(args));
mc_vector_(vec, args...);
return vec;
}
And actually, i would like to know if you image a smarter way of doing this.
| You need to put the variadic argument last and you could use a fold-expression to populate vec. You could also make it do perfect forwarding:
#include <utility> // std::forward
template<typename... Args, typename T>
void mc_vector_(vector<MyClass>& vec, T&& t, Args&&... args) {
vec.emplace_back(std::forward<T>(t));
(mc_vector_(vec, std::forward<Args>(args)), ...); // fold-expression
}
template<typename ...Args>
vector<MyClass> mc_vector(Args&&... args) {
vector<MyClass> vec;
vec.reserve(sizeof...(args));
mc_vector_(vec, std::forward<Args>(args)...);
return vec;
}
The top function could be simplified to:
template<typename... Args>
void mc_vector_(vector<MyClass>& vec, Args&&... args) {
(vec.emplace_back(std::forward<Args>(args)), ...); // fold-expression
}
If you really want a recursive call:
template<typename... Args, typename T>
void mc_vector_(vector<MyClass>& vec, T&& t, Args&&... args) {
vec.emplace_back(std::forward<T>(t));
if constexpr (sizeof...(Args) > 0) mc_vector_(vec, std::forward<Args>(args)...);
}
|
70,327,648 | 70,327,670 | Overloading << and >> as outside member functions for template class | I am trying to define my operator overloading outside the class like this:
template <typename Type>
class myClass
{
...
friend std::ostream& operator << (std::ostream&, const myClass&);
friend std::istream& operator >> (std::istream&, myClass&);
...
}
template <typename Type>
std::ostream& myClass<Type> :: operator << (std::ostream& out, const myClass<Type>& other) { ... }
template <typename Type>
std::istream& myClass<Type> :: operator >> (std::istream& in, myClass<Type>& other) { ... }
My problem is that I get an error saying something like "class template class has no member operator<<" and I do not understand how or why is this happening.
| For starters the friend functions are not member functions of the class where they are decalred.
So these declarations in any case are incorrect.
template <typename Type>
std::ostream& myClass<Type> :: operator << (std::ostream& out, const myClass<Type>& other) { ... }
template <typename Type>
std::istream& myClass<Type> :: operator >> (std::istream& in, myClass<Type>& other) { ... }
Secondly within the class definition you declared non-template friend functions.
Either you need to provide their definitions within the class definition. Or for each potential template argument of the class you have to define the friend functions outside the class.
Here is a demonstration program that shows how to define a non-template friend function within the class template definition.
#include <iostream>
template <typename T>
class A
{
private:
T t;
public:
A( const T &t ) : t( t ) {}
friend std::ostream &operator <<( std::ostream &os, const A &a )
{
return os << a.t;
}
};
int main()
{
std::cout << A<int>( 10 ) << '\n';
std::cout << A<const char *>( "Hello" ) << '\n';
}
The program output is
10
Hello
And here is a demonstration program that shows how to define the friend functions outside the class template definition. That is for each used specialization of the class template you need to define the non-template friend functions.
#include <iostream>
template <typename T>
class A
{
private:
T t;
public:
A( const T &t ) : t( t ) {}
friend std::ostream &operator <<( std::ostream &os, const A &a );
};
std::ostream &operator <<( std::ostream &os, const A<int> &a )
{
return os << a.t;
}
std::ostream &operator <<( std::ostream &os, const A<const char *> &a )
{
return os << a.t;
}
int main()
{
std::cout << A<int>( 10 ) << '\n';
std::cout << A<const char *>( "Hello" ) << '\n';
}
An alternative approach is to declare template friend functions. For example
#include <iostream>
template <typename T>
class A
{
private:
T t;
public:
A( const T &t ) : t( t ) {}
template <typename T>
friend std::ostream &operator <<( std::ostream &os, const A<T> &a );
};
template <typename T>
std::ostream &operator <<( std::ostream &os, const A<T> &a )
{
return os << a.t;
}
int main()
{
std::cout << A<int>( 10 ) << '\n';
std::cout << A<const char *>( "Hello" ) << '\n';
}
|
70,327,741 | 70,327,918 | Is it possible to write multiple characters in C++ Assembly with no stdlib? | I am developing a operating system, following this tutorial, and I'm on part 7 (chapter 7), and he shows how to print a character to the screen, but I want to print multiple characters but it just overwrites the previous character. Here is my code
extern "C" void main() {
// printf("Hello, World!");
*(char *)0xb8000 = 'H';
*(char *)0xb8000 = 'e';
*(char *)0xb8000 = 'l';
*(char *)0xb8000 = 'l';
*(char *)0xb8000 = 'o';
*(char *)0xb8000 = ',';
*(char *)0xb8000 = ' ';
*(char *)0xb8000 = 'W';
*(char *)0xb8000 = 'o';
*(char *)0xb8000 = 'r';
*(char *)0xb8000 = 'l';
*(char *)0xb8000 = 'd';
*(char *)0xb8000 = '!';
return;
}
| @user2864740 sent me a link that helped me fix it, as it turns out, every 2nd character written to 0xB8000 is a color.
So if you wanted to print Hello!, I'm pretty sure you would do
*(char*)0xB8000 = "H";
*(char*)0xB8001 = 15;
*(char*)0xB8002 = "e";
*(char*)0xB8003 = 15;
*(char*)0xB8004 = "l";
*(char*)0xB8005 = 15;
*(char*)0xB8006 = "l";
*(char*)0xB8007 = 15;
*(char*)0xB8008 = "o";
*(char*)0xB8008 = 15;
*(char*)0xB8009 = "!";
*(char*)0xB800a = 15;
(untested)
|
70,327,977 | 70,328,175 | How to Manually call a Destructor on a Smart Pointer? | I have a shared_ptr for an SDL_Texture in a game I'm making. I want to use a shared pointer to be able to use the same texture on multiple objects without leaking any memory. I have the shared pointer return from a method which is
std::shared_ptr<SDL_Texture> RenderWindow::loadTexture(const char *filePath) {
return std::shared_ptr<SDL_Texture>(IMG_LoadTexture(renderer, filePath),
SDL_DestroyTexture);
}
However, when I'm done using the texture in the game, I want to be able to manually call it's destructor, which is SDL_DestroyTexture however that doesn't get called when I need it to and it takes up a lot of memory. Is there any way of telling it to call its destructor when I want it to?
| You can release the ownership of the object by calling reset() on the shared_ptr. If that is the last one holding the pointer, the shared_ptr's deleter member will be used to destroy the object.
https://en.cppreference.com/w/cpp/memory/shared_ptr/reset
|
70,328,542 | 70,328,632 | While loop and do while loop only running once in a calculator program. C++ | Was trying to run a simple calculator using a while loop and internal class. My issue is that I used a while loop that had the condition that when a boolean called flag is equal to true it would continually run the program over and over. To exit the while loop I included a section to ask the user if it wanted to continue and allowed them to input a value to the flag. No matter how many different versions of the conditions I use the loop only runs with once. I currently have a do while loop that checks if an int called loop is less than 2 which is initialized to have the value of 1. After presenting the value it increments int loop so that it is 2 and doesn't meet the loop requirements. Then asks the user if they want to continue, which if true resets the value to 1. Still hasn't worked and nothing online has shown the same issue or a solution, even in different languages. Thank you to any additions.
Code: (C++)
// main.cpp
// Calculator
//
// Created by yared yohannes on 12/10/21.
//
class calculation{
public:
calculation(){
}
int add(int first, int second){
int result= first+second;
return result;
}
int minus(int first, int second){
int result= first-second;
return result;
}
int multi(int first, int second){
int result= first*second;
return result;
}
int divide(int first, int second){
int result= first/second;
return result;
}
};
#include <iostream>
using namespace std;
int main(){
int first=0,second=0;
bool flag=true;
char sign;
int loop=1;
calculation calc;
cout<<"Welcome to the calculator program.\n";
do{
cout<<"Please enter the first value: ";
cin>>first;
cout<<"Please enter the desired operation(+,-,*,/): ";
cin>>sign;
cout<<"Please enter the second value: ";
cin>>second;
if(sign=='+'){
cout<<calc.add(first, second)<<"\n";
}
else if(sign=='-'){
cout<<calc.minus(first, second)<<"\n";
}
else if(sign=='*'){
cout<<calc.multi(first, second)<<"\n";
}
else if(sign=='/'){
cout<<calc.divide(first, second)<<"\n";
}
cout<<"Do you want to continue(true or false): ";
cin >> flag;
loop++;
if(flag==true){
loop=1;
}
}while(loop<2);
}
| In C++ bools are stored as 0 or 1 values. 0 is false and 1 is true. If you're putting in "true" for the cin statement it won't work so loop will always increase. What you have to do is put in 0 or 1 into the console. You could also store the input as a string and use if statements to check if it is "true" or "false" and set the boolean value based on that. Like this:
#include <string>
/*
The code you have
*/
int main() {
string booleanInput;
//Code you have
cin >> booleanInput;
if(booleanInput == "true") {
flag = true;
} else if(booleanInput == "false") {
flag = false;
}
//Other code you have
}
|
70,329,898 | 70,329,970 | Specialization doesn't contain data that's declared in the primary template | class Base {
public:
virtual void load() = 0;
};
template<typename T>
class CustomConfig : public Base {
public:
const T& getData() { return data; }
T data;
};
template<>
class CustomConfig<std::set<uint32_t>> {
public:
virtual void load() {
this->data = {4, 5, 6};
}
};
I don't know why I got the error:
class CustomConfig<std::set<unsigned int> >' has no member named 'data'
REAL CASE
In fact, I got such an issue: I need a virtual function, but it's return type is not unique, it may be a std::set, a std::vector, std::list or some other types. Then I was thinking the template technique might help. That's why I defined the class template<typename T> class CustomConfig.
I hope this was not a serious XY problem... Obviously I misunderstood how template class works.
| To provide an alternative to the other answers, which all say you must add your data member, there's another option which is to derive from a template instantiation instead:
class CustomConfigSetOfUInt : public CustomConfig<std::set<uint32_t>> {
public:
void load() override {
this->data = {4, 5, 6};
}
};
If your CustomConfig provides other generalized functionality that would benefit from being done in the class template, then you might prefer this approach. Your design in general is a bit uncomfortable and does seem to have a "relaxed" attitude toward encapsulation either way. You may want to have a deeper think about it.
|
70,330,230 | 70,330,660 | Read 2d array from txt file in c++ | This is my code
#include<bits/stdc++.h>
using namespace std;
int main()
{
char arr1[10][10];
cout << "Reading Start" << endl;
ifstream rfile("test.txt");
rfile.getline(arr1[10], 10);
int i, j;
for (i = 0; i < 6; i++)
{
for (j = 0; i < 6; j++)
{
cout << arr1[i][j];
}
}
cout << "\nRead Done" << endl << endl;
rfile.close();
}
This is my test.txt file
0 4 7 0 0 0
4 0 0 5 3 0
7 0 0 0 6 0
0 5 3 0 0 2
0 3 4 0 0 2
0 0 0 2 2 0
I want to read this matrix but when using the above code then it shows core dumped output, can anyone give me a better solution to do this thing?
| There are a lot of other ways to perform the specific task, but i guess your method is not wrong, and you have just made a simple typing mistake in your second for loop condition. so ill just fix your code for you.
and also you could just input single values at a time as u go.
#include<bits/stdc++.h>
using namespace std;
int main()
{
char arr1[10][10];
cout <<"Reading Start" <<endl;
ifstream rfile("test.txt");
int i,j;
for(i=0;i<6;i++){
for(j=0;j<6;j++){
rfile >> arr1[i][j];
cout << arr1[i][j] << " ";
}
cout << endl;
}
cout <<"\nRead Done" <<endl<<endl;
rfile.close();
}
Output :
|
70,330,314 | 70,331,227 | Shortest path question involving transfer in cyclic graph | I'm trying to solve a problem of graph:
There are (n+1) cities(no. from 0 to n), and (m+1) bus lines(no. from 0 to m).
(A line may contain repeated cities, meaning the line have a cycle.)
Each line covers several cities, and it takes t_ij to run from city i to city j (t_ij may differ in different lines).
Moreover, it takes extra transfer_time to each time you get in a bus.
An edge look like this: city i --(time)-->city2
Example1:
n = 2, m = 2, start = 0, end = 2
line0:
0 --(1)--> 1 --(1)--> 2; transfer_time = 1
line1:
0 --(2)--> 2; transfer_time = 2
Line0 take 1+1+1 = 3 and line1 takes 4, so the min is 3.
Example2:
n = 4, m = 0, start = 0, end = 4
line0:
0 --(2)--> 1 --(3)--> 2 --(3)-->3 --(3)--> 1 --(2)--> 4; transfer_time = 1
it takes 1(get in at 0) + 2(from 0 to 1) + 1(get off and get in, transfer) + 2 = 6
I've tried to solve it with Dijkstra Algorithm, but failed to handle graph with cycles(like Example2).
Below is my code.
struct Edge {
int len;
size_t line_no;
};
class Solution {
public:
Solution() = default;
//edges[i][j] is a vector, containing ways from city i to j in different lines
int findNearestWay(vector<vector<vector<Edge>>>& edges, vector<int>& transfer_time, size_t start, size_t end) {
size_t n = edges.size();
vector<pair<int, size_t>> distance(n, { INT_MAX / 2, -1 }); //first: len, second: line_no
distance[start].first = 0;
vector<bool> visited(n);
int cur_line = -1;
for (int i = 0; i < n; ++i) {
int next_idx = -1;
//find the nearest city
for (int j = 0; j < n; ++j) {
if (!visited[j] && (next_idx == -1 || distance[j].first < distance[next_idx].first))
next_idx = j;
}
visited[next_idx] = true;
cur_line = distance[next_idx].second;
//update distance of other cities
for (int j = 0; j < n; ++j) {
for (const Edge& e : edges[next_idx][j]) {
int new_len = distance[next_idx].first + e.len;
//transfer
if (cur_line == -1 || cur_line != e.line_no) {
new_len += transfer_time[e.line_no];
}
if (new_len < distance[j].first) {
distance[j].first = new_len;
distance[j].second = e.line_no;
}
}
}
}
return distance[end].first == INT_MAX / 2 ? -1 : distance[end].first;
}
};
Is there a better practice to work out it? Thanks in advance.
| Your visited set looks wrong. The "nodes" you would feed into Djikstra's algorithm cannot simply be cities, because that doesn't let you model the cost of switching from one line to another within a city. Each node must be a pair consisting of a city number and a bus line number, representing the bus line you are currently riding on. The bus line number can be -1 to represent that you are not on a bus, and the starting and destination nodes would have a bus line numbers of -1.
Then each edge would represent either the cost of staying on the line you are currently on to ride to the next city, or getting off the bus in your current city (which is free), or getting on a bus line within your current city (which has the transfer cost).
You said the cities are numbered from 0 to n but I see a bunch of loops that stop at n - 1 (because they use < n as the loop condition), so that might be another problem.
|
70,330,570 | 70,331,147 | How are pairs stored in memory in C++? | I was just reading about pairs in C++ when this doubt stroke my mind that how the pairs are stored in memory and id the identifier assigned to the pairs a object or something else.
pls explain how an array containing pair uses memory to save the pairs and how can we iterate through the that array, by accessing each pair;
| As for the pair itself, if you take a look at the standard library source code you'll just notice, that after cutting all the boilerplate, the for the most trivial case std::pair is just a simple class template:
template<typename First, typename Second>
struct pair
{
First first;
Second second;
};
Now, all the boilerplate is there to ensure the all the special functions like comparison, assignment, copy construction etc. are performed with minimal overhead.
But for the sake of mental model one can think of this simple struct.
As for "array of pairs" - I'm not sure I follow, really.
std::array<std::pair<X,Y>, SIZE>/std::vector<std::pair<X,Y>> behaves just as it would for any other type, i.e. it store the pairs in contiguous memory block, end of story.
Same about iteration, there's nothing special about it:
std::array<std::pair<char, int>, 3> pairs{
std::pair{'a', 1},
std::pair{'b', 2},
std::pair{'c', 3}};
for (const auto& p:pairs){
std::cout << p.first << " " << p.second << "\n";
}
demo
|
70,331,033 | 70,331,080 | Vector parameter in a function doesn't seem to actually apply to input? | I have a vector variable named intVec, and I have a function named pushBack, that accepts a vector of type integer just like intVec, but when I actually pass that vector into the function in order to push_back the x parameter, nothing seems to happen.
Output expected from intVec.size() is 1
Output given from intVec.size() is 0
I'm genuinely confused as to what I'm doing incorrectly here.
Perhaps I'm missing something extremely obvious.
#include <vector>
std::vector<int> intVec;
void pushBack(int x, std::vector<int> vec) {
vec.push_back(x);
}
int main() {
pushBack(10, intVec);
std::cout << intVec.size();
}
| That is because you pass the vector by value instead of by reference (or pointer).
This means, that when you call the function, the vector you call 'push_back' on is actually an independent copy of the original vector, which get deallocated upon leaving the function.
Try this header instead:
void pushBack(int x, std::vector<int> &vec) {
vec.push_back(x);
}
The & tells the compiler to pass by reference, meaning that whatever you do to vec, you also do to the vector you originally passed.
|
70,331,109 | 70,406,085 | Visual Studio Code "python.h: No such file or directory" windows gcc | I 'm a total beginner in C++ and getting crazy trying to embed Python in C++ using VS Code IDE and GCC compiler.
I am stock and now I 'm keep facing this silly error that says:
python.h: No such file or directory gcc
I have followed steps explaned in "Using GCC with MinGW in VS Code" in order to configure C++ in VS Code but I failed to install MinGW (The bin folder was empty) so I add already installed CodeBlocks MinGW to my path and it seems to work.
I have python 3.8 installed and tried other solutions and already put Python.h and python library path in project include path.
"C:/Users/MPC/AppData/Local/Programs/Python/Python38-32/include/"
and
"C:/Users/MPC/AppData/Local/Programs/Python/Python38-32/libs/"
here is the code that I want to compile:
#include <stdio.h>
#include <conio.h>
#include <python.h>
int main()
{
PyObject* pInt;
Py_Initialize();
PyRun_SimpleString("print('Hello World from Embedded Python!!!')");
Py_Finalize();
printf("\nPress any key to exit...\n");
if(!_getch()) _getch();
return 0;
}
and this is my c_cpp_properties.json. (C++ configuration file):
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**",
"C:/Users/MPC/AppData/Local/Programs/Python/Python38-32/include/**",
"C:/Users/MPC/AppData/Local/Programs/Python/Python38-32/libs/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.18362.0",
"compilerPath": "C:/Program Files (x86)/CodeBlocks/MinGW/bin/gcc.exe",
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "windows-gcc-x86"
}
],
"version": 4
}
and this is tasks.json file:
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: gcc.exe build active file",
"command": "C:/Program Files (x86)/CodeBlocks/MinGW/bin/gcc.exe",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "C:/Program Files (x86)/CodeBlocks/MinGW/bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compiler: \"C:/Program Files (x86)/CodeBlocks/MinGW/bin/gcc.exe\""
}
]
}
| The problem was a combinations of simple mistakes and as a beginner I solved it by some digging in gcc -l -L option flags for library link example and gcc arguments docs.
There are several simple and important points that should be observed:
1. The order of options is really important. If its wrong, compiler wont work. It should be like -I(capital i),-g,-L,-l(lower case L),-o.
2. To embed python in C++ firstly the path to python include files have to be known to compiler by -I option. Then the path to python libraries by a -L option. Then name of the each required python .lib file contained in libs folder of python.
Here is an example of it:
"-IC:/Users/MPC/AppData/Local/Programs/Python/Python38-32/include",=>(path to python include files)
"-g",=>(debug option specified by ide)
"${file}",
"-LC:/Users/MPC/AppData/Local/Programs/Python/Python38-32/libs",=>(path to python libraries)
"-lpython38",=>(python lib contained in python libs)
"-lpython3",=>(python lib contained in python libs)
"-l_tkinter",=>(python lib contained in python libs)
"-o",=>(output argument specified by ide)
"${fileDirname}\\${fileBasenameNoExtension}.exe"
I hope that with this answer, the beginners like me, get to the conclusion faster.
There is also a good youtube tutorial of Embedding python in C++ with CMake and Pybind11 and VS Code
|
70,331,486 | 70,331,660 | Second function with same integers doesn't work | I have a task to create 2 functions to calculate GCD and LCM. But I noticed that my second function doesn't work not matter what calculation is there. What am I doing wrong ?
#include <iostream>
using namespace std;
int gcd(int number1,int number2);
int lcm(int number1,int number2);
int main()
{
int number1;
int number2;
cout<<"enter number 1: ";
cin>>number1;
cout<<"enter number 2: ";
cin>>number2;
cout<<"The GCD of "<<number1<<" and "<<number2<<" is "<<gcd(number1,number2)<<endl;
cout<<"The LCM of "<<number1<<" and "<<number2<<" is "<<lcm(number1,number2)<<endl;
return 0;
}
int gcd(int number1,int number2)
{
if (number2==0)
return number1;
return gcd(number2,number1 % number2);
}
int lcm(int number1,int number2)
{
return lcm(number2, number1 * number2)/gcd(number1,number2);
}
Output:
enter number 1: 44
enter number 2: 121
The GCD of 44 and 121 is 11
The LCM of 44 and 121 is
Process returned -1073741571 (0xC00000FD)
| The problem lies within the lcm() function:
int lcm(int number1,int number2)
{
return lcm(number2, number1 * number2)/gcd(number1,number2);
}
This function will be an infinite recursion because there's no base case. Eventually, you will run into, ironically, a stack overflow problem.
Looking at the nature of the function, I think what you meant is:
int lcm(int number1, int number2)
{
return number1 * number2 / gcd(number1, number2);
}
|
70,331,741 | 70,333,341 | Find the biggest element in range that matches condition | Lets say I have range of integers [l, r) and a function check(int idx) which satisfies the following condition:
there is an index t (l <= t < r) such that for each i (l <= i <= t) check(i) == true and for each j (t < j < r) check(j) == false. Is there a standard way to find index t?
Standard binary_search() needs comparator that takes two arguments, so it can't be applied here (correct me if I'm wrong).
| Assuming you are searching for a continuous range of integers (and not, for example, an indexed array) I would suggest a dichotomic search:
int find_t(int l, int r) {
// Preconditions
assert(check(l) == true);
//assert(check(r) == false); // this precondition is not mandatory
int max_idx_true = l; // highest known integer which satisfies check(idx) == true
int min_idx_false = r; // lowest known integer which satisfies check(idx) == false
while (max_idx_true+1 < min_idx_false) {
int mid_idx = (max_idx_true+min_idx_false)/2;
if (check(mid_idx)) max_idx_true = mid_idx;
else min_idx_false = mid_idx;
}
int t = max_idx_true;
// Postconditions
assert(check(t) == true);
assert(t+1 == r || check(t+1) == false);
return t;
}
This algorithm narrows the closest integers where check(idx) is true and the next one is false. In your case, you are looking for t which corresponds to max_idx_true.
It should be noted that the following preconditions must be satisfied for this to work:
l < r
check(l) is true
for any idx, if check(idx) is true then check(idx-1) is always true
for any idx, if check(idx) is false then check(idx+1) is always false
Below is a source code example for testing the algorithm and output lines to better understand how it works. You can also try it out here.
#include <iostream>
#include <cassert>
using namespace std;
// Replace this function by your own check
bool check(int idx) {
return idx <= 42;
}
int find_t(int l, int r) {
assert(check(l) == true);
//assert(check(r) == false); // this precondition is not mandatory
int max_idx_true = l; // highest known integer which satisfies check(idx) == true
int min_idx_false = r; // lowest known integer which satisfies check(idx) == false
int n = 0; // Number of iterations, not needed but helps analyzing the complexity
while (max_idx_true+1 < min_idx_false) {
++n;
int mid_idx = (max_idx_true+min_idx_false)/2;
// Analyze the algorithm in detail
cerr << "Iteration #" << n;
cerr << " in range [" << max_idx_true << ", " << min_idx_false << ")";
cerr << " the midpoint " << mid_idx << " is " << boolalpha << check(mid_idx) << noboolalpha;
cerr << endl;
if (check(mid_idx)) max_idx_true = mid_idx;
else min_idx_false = mid_idx;
}
int t = max_idx_true;
assert(check(t) == true);
assert(t+1 == r || check(t+1) == false);
return t;
}
int main() {
// Initial constants
int l = 0;
int r = 100;
int t = find_t(l, r);
cout << "The answer is " << t << endl;
return 0;
}
The main advantage of the dichomotic search is that it finds your candidate with a complexity of only O(log2(N)).
For example if you initialize int l = -2000000000 and int r = 2000000000 (+/- 2 billions) you need to known the answer in about 4 billion numbers, yet the number of iterations will be 32 at worst.
|
70,332,218 | 70,332,351 | Template class char*, return type of function const char*? | I have this templated base class:
template <class V>
class ValueParam
{
public:
virtual V convert(const char* f) const = 0;
protected:
V val;
};
Note that I can store some value val that has type V, and that I have a convert function that automatically returns the right type when I call it on a ValueParam object.
An example with int as type V:
class IntParam : public ValueParam<int>
{
public:
IntParam(int i) { val = i; }
int convert(const char* f) const override { return atoi(f); }
};
Which we can then use:
IntParam i(1234); // The value of val is 1234
int x = i.convert("1"); // x will be 1
Now I bump into a problem when using char* as my type V:
class StrParam : public ValueParam<char*>
{
public:
StrParam(const char* str, size_t max_len)
{
val = new char[max_len + 1]{};
strncpy(val, str, max_len + 1);
}
~StrParam() { delete[] val; }
char* convert(const char* f) const override { return f; } // Doesn't compile: f is const char*
};
I don't want to do any const-casting.
Luckily, I don't need the result of convert to be mutable in any way. Could I change its return type to something that does compile?
And what would that type be? Because just changing it to virtual const V convert... would mean the return type in StrParam would become char* const convert... and that obviously still doesn't work.
| You can add const on the pointed type for the return type:
// for non-pointer type
template <typename T>
struct add_const_pointee { using type = T; };
// for pointer type
template <typename T>
struct add_const_pointee<T*> { using type = const T*; };
// helper type
template <typename T>
using add_const_pointee_t = typename add_const_pointee<T>::type;
template <class V>
class ValueParam
{
public:
virtual add_const_pointee_t<V> convert(const char* f) const = 0;
// ^^^^^^^^^^^^^^^^^^^^^^
protected:
V val;
};
and
class StrParam : public ValueParam<char*>
{
public:
StrParam(const char* str, size_t max_len)
{
val = new char[max_len + 1]{};
strncpy(val, str, max_len + 1);
}
~StrParam() { delete[] val; }
const char* convert(const char* f) const override { return f; }
// ^^^^^
};
|
70,332,332 | 70,332,479 | How to use vector as a private member in class to store and pass data | Assuming that there is a Class called Solution:
class Solution{
private:
int COL;
int ROW;
vector<vector <int>> grid(ROW, vector<int>(COL));
public:
void setData();
};
Then put the definition of function setData()
void Solution::setData(){
for (int i = 0; i < ROW; i++){
for (int j = 0; j < COL; j++){
grid[i][j] = 1;
}
}
}
Firstly, in the declaration of vector grid, ROW and COL is unread;
Secondly, if I revise the declaration of grid as vector<vector<int>> grid(100, vector<int>(100))(namely, define dimension of vector clearly), it then lose the feature of dynamic
Last, if I revise the declaration of vector grid, the programme would be interrupted when running setData()
Sincerely thank you for any suggestions!
thanks for you guys, I defined the constructor function:
Solution(){
ROW = 100;
COL = 100;
}
however, COL and ROW is also unreadable in definition of grid(vector<vector>)
thank you!
| Currently your definition of grid
vector<vector <int>> grid(ROW, vector<int>(COL));
looks rather like a function. State it's type and name, and initialise elsewhere to avoid this:
class Solution {
private:
const int COL;
const int ROW;
vector<vector <int>> grid;
public:
void setData();
Solution() :
ROW{ 10 },
COL {5 },
grid(ROW, vector<int>(COL))
{}
};
I made the sizes const, cos they are for the lifetime of your Solution, I presume.
You can change the constructor to take the values for the row and column and pass them in, rather than use the magic number I chose.
|
70,332,551 | 70,435,231 | How to share a view model in C++ UWP? | How can I share a view model between different pages in a C++ UWP application?
This answer is a C# solution which uses a static property:
public sealed partial class MainPage : Page
{
public AppViewModel ViewModel { get; set; } = new AppViewModel();
public static MainPage Current { get; set; }
public MainPage()
{
this.InitializeComponent();
Current = this;
}
}
But I am having trouble translating that into C++.
My C++ MainPage currently looks like this:
namespace winrt::myproject::implementation
{
struct MainPage : MainPageT<MainPage>
{
MainPage();
myproject::MainViewModel MainViewModel() const { return this->mainViewModel; }
private:
myproject::MainViewModel mainViewModel{ nullptr };
};
}
The view model instance is created in the MainPage() constructor using
this->mainViewModel = winrt::make<myproject::implementation::MainViewModel>();
And the .idl file simply lists the view model instance as a property:
[default_interface]
runtimeclass MainPage : Windows.UI.Xaml.Controls.Page
{
MainPage();
MainViewModel MainViewModel{ get; };
}
How can I share the MainViewModel between all of my pages?
What do I need to change in the .idl and in the .h file?
Do I need to use std::shared_ptr<myproject::MainViewModel> or winrt::comptr<myproject::MainViewModel> to avoid copying the struct and to really share the same instance?
| myproject::MainViewModel ultimately derives from winrt::Windows::Foundation::IUnknown. It is this structure that implements all the reference counting machinery, turning each derived type into a shared pointer to its interface.
The following implementation
myproject::MainViewModel MainViewModel() const { return this->mainViewModel; }
invokes the IUnknown::IUnknown(IUnknown const& other) copy-c'tor that increments the reference count on other and constructs an IUnknown instance holding the same pointer. Both this->mainViewModel and the return value point to the same object.
In general, copying structures that represent projected types performs a shallow copy. Only the pointer to the object is copied, and the reference count is incremented. Like a std::shared_ptr the operation is thread-safe and has comparable overhead.
A lot more information on the internals and use of projected types can be found at Consume APIs with C++/WinRT.
|
70,332,819 | 70,332,832 | "No default constructor exists for class" if I want to construct a class with another one | I have a class named Ball and I want to create a class Particle with, in its constructor, a std::vector<Ball> particles, but I'm getting the error "No default constructor exists for class 'Ball'"
The Ball.h file :
#pragma once
#include <vector>
#include <raylib.h>
class Ball {
private:
Vector3 position;
Vector3 speed;
float radius;
public:
Ball(Vector3 ballPosition, Vector3 ballSpeed,float ballRadius);
};
The Ball.cpp file :
#include "Ball.h"
#include <raymath.h>
#include <rlgl.h>
Ball::Ball(Vector3 position, Vector3 speed,float radius) {
this->position = position;
this->speed = speed;
this->radius = radius;
}
The Particles.h file :
#pragma once
#include <vector>
#include <raylib.h>
#include <Ball.h>
class Particles{
private:
std::vector<Ball> particles;
std::vector<Vector3> velocities;
float w;
float c1;
float c2;
public:
Particles(std::vector<Ball> particles, std::vector<Vector3> velocities, float w, float c1, float c2);
};
The Particles.cpp file (where the error is):
#include "Ball.h"
#include <raymath.h>
#include <rlgl.h>
#include "Particles.h"
Particles::Particles(std::vector<Ball> particles, std::vector<Vector3> velocities, float w, float c1, float c2) {
this->particles = particles;
this->velocities = velocities;
this->w = w;
this->c1 = c1;
this->c2 = c2;
}
| The problem is that since you have a parameterized constructor for your class Ball, the compiler will not synthesize a default constructor by itself. So if you want to create/construct an object of class Ball using a default constructor, say by writing Ball b;, then you must first provide a default constrcutor for class Ball as shown below.
Solution 1
Just add a default constrctor in class Ball as shown below:
Ball.h
class Ball {
private:
Vector3 position;
Vector3 speed;
float radius = 0;//use in-class initializer
public:
Ball(Vector3 ballPosition, Vector3 ballSpeed,float ballRadius);
Ball() = default; //DEFAULT CONSTRUCTOR ADDED
};
Alternative Method of adding constructor
Another way of adding a default constructor would be as shown below:
Ball.h
#pragma once
#include <vector>
#include <raylib.h>
class Ball {
private:
Vector3 position;
Vector3 speed;
float radius = 0;//use IN-CLASS INITIALIZER
public:
Ball(Vector3 ballPosition, Vector3 ballSpeed,float ballRadius);
Ball(); //declaration for default constrctor
};
Ball.cpp
#include "Ball.h"
#include <raymath.h>
#include <rlgl.h>
Ball::Ball(Vector3 position, Vector3 speed,float radius) {
this->position = position;
this->speed = speed;
this->radius = radius;
}
//define the default constructor
Ball::Ball()
{
cout << "default constructor" << endl;
//do other things here if needed
}
|
70,332,983 | 70,357,585 | How to completely omit CBC loggings in C++? | I'm using the CBC solver to solve a program, and the method model.branchAndBound is called for multiple times(quite many). Because the log messages have to be written to file, so it is actually slowing down the program. I wonder is it possible to ommit the log messages entirely? This is in c++, and I now think that many suggested answer pulp is only possible for python. Also, in case pulp is the solution to this problem I'm not so sure about how pulp is used. Is there any good documentation to help understand the relationship between pulp and CBC, and how to use them? If anyone could help me with this, I'd be real grateful!
For example(this is an example from github):
// Copyright (C) 2009, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
// For Branch and bound
#include "OsiSolverInterface.hpp"
#include "CbcModel.hpp"
// Methods of building
#include "CoinBuild.hpp"
#include "CoinModel.hpp"
int main(int argc, const char *argv[])
{
OsiClpSolverInterface model;
double objValue[] = { 1.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, -1.0 };
// Lower bounds for columns
double columnLower[] = { 2.5, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0 };
// Upper bounds for columns
double columnUpper[] = { COIN_DBL_MAX, 4.1, 1.0, 1.0, 4.0,
COIN_DBL_MAX, COIN_DBL_MAX, 4.3 };
// Lower bounds for row activities
double rowLower[] = { 2.5, -COIN_DBL_MAX, 4.0, 1.8, 3.0 };
// Upper bounds for row activities
double rowUpper[] = { COIN_DBL_MAX, 2.1, 4.0, 5.0, 15.0 };
// Matrix stored packed
int column[] = { 0, 1, 3, 4, 7,
1, 2,
2, 5,
3, 6,
0, 4, 7 };
double element[] = { 3.0, 1.0, -2.0, -1.0, -1.0,
2.0, 1.1,
1.0, 1.0,
2.8, -1.2,
5.6, 1.0, 1.9 };
int starts[] = { 0, 5, 7, 9, 11, 14 };
// Integer variables (note upper bound already 1.0)
int whichInt[] = { 2, 3 };
int numberRows = (int)(sizeof(rowLower) / sizeof(double));
int numberColumns = (int)(sizeof(columnLower) / sizeof(double));
CoinModel build;
// First do columns (objective and bounds)
int i;
for (i = 0; i < numberColumns; i++) {
build.setColumnBounds(i, columnLower[i], columnUpper[i]);
build.setObjective(i, objValue[i]);
}
// mark as integer
for (i = 0; i < (int)(sizeof(whichInt) / sizeof(int)); i++)
build.setInteger(whichInt[i]);
// Now build rows
for (i = 0; i < numberRows; i++) {
int startRow = starts[i];
int numberInRow = starts[i + 1] - starts[i];
build.addRow(numberInRow, column + startRow, element + startRow,
rowLower[i], rowUpper[i]);
}
// add rows into solver
model.loadFromCoinModel(build);
CbcModel model2(model);
model2.branchAndBound();
return 0;
}
and the log outputs are:
Clp0000I Optimal - objective value 3.2368421
Clp0000I Optimal - objective value 3.2368421
Node 0 depth 0 unsatisfied 0 sum 0 obj 3.23684 guess 3.23684 branching on -1
Clp0000I Optimal - objective value 3.2368421
Cbc0004I Integer solution of 3.2368421 found after 0 iterations and 0 nodes (0.13 seconds)
Cbc0001I Search completed - best objective 3.236842105263158, took 0 iterations and 0 nodes (0.14 seconds)
Cbc0035I Maximum depth 0, 0 variables fixed on reduced cost
Clp0000I Optimal - objective value 3.2368421
Clp0000I Optimal - objective value 3.2368421
| Adding this to the code solves everything:
model.setLogLevel(0);
|
70,333,392 | 70,333,454 | declaring a variable in if statement | Please condiser the following snippet
//foo is just a random function which returns error code
if(int err = foo() == 0){
//err should contain the error code
...
}
The problem with that is err contains the result of foo() == 0, and what I want to evalute is int err = foo(); then if(err == 0) but inside the if statement.
I have already tried if((int err = foo()) == 0) and it doesn't work.
Also, I don't want to do int err; if((err = foo) != 0)).
Is this possible ?
| For C++ 17 and onwards you can use if statements with initializers:
if (int err = foo(); err == 0) {
...
}
|
70,333,411 | 70,333,523 | my code works but it does not give me what I want | my code is going to take ten numbers and separate the numbers to two groups : odd and positive numbers
#include <iostream>
using namespace std;
int odd(int a)
{
if (a % 2 != 0)
{
return a;
}
}
int pos(int p)
{
if (p >= 0)
{
return p;
}
}
int main()
{
int i;
int entery[10];
cout << "please enter ten number : ";
for (i = 0; i < 10; i++)
{
cin >> entery[i];
}
cout << "the odd numbers are : \n" << odd(entery[i]);
cout << "your positive numbers are : \n" << pos(entery[i]);
}
it it somehow works but the odd number is always 0
and the positive number always is -858993460
I use it without array and both groups become zero
| Here it goes your code corrected. Just to let you know, your code wasn't checking all the possible conditions inside odd and pos functions. It just was returning something when the condition was false.
I modified these functions, making it work with a bool now instead of a number. In your main method, now, when this functions returns a true, it will print the number, but won't do it if it's returning a false.
#include <iostream>
using namespace std;
bool odd(int a) { return a % 2 != 0; }
bool pos(int p) { return p >= 0; }
int main()
{
int i;
int entery[10];
cout << "Please enter ten numbers: ";
for (i = 0; i < 10; i++)
cin >> entery[i];
cout << "The odd numbers are : ";
for(int i = 0; i < 10; i++) {
if (odd(entery[i]))
cout << entery[i] << " ";
}
cout << "\nYour positive numbers are: ";
for(int i = 0; i < 10; i++) {
if (pos(entery[i]))
cout << entery[i] << " ";
}
}
If you want to change your program in the future, you can change the for to make it work while sizeof(entery)/sizeof(entery[0]), so it will iterate the array looking at the size instead of the number 10.
|
70,333,521 | 70,335,279 | Handling all symbols combinations in makefile | Say I have designed a C++ library, and I want to extensively test all the features.
Some of these features are defined at build-time, through symbols that are defined or not.
// library.h
A foo( const B& b )
{
#ifdef OPTION_X
... do it that way
#else
... do it another way
#endif
}
I build a test program that I want to build and run for all possible configurations, to make sure all tests pass:
// mytest.cpp
#include "library.h"
int main()
{
... some test code
#ifdef OPTION_X
... do it that way
#else
... do it that other way
#endif
... more stuff with more options
}
If I have 1 option (call it "A"), I want to run the tests if it is "on"
(_AY for option "A": Yes) or "off" (_AN for option "A": No)
My makefile holds this:
.PHONY: test
test: BUILD/mytest_AY BUILD/mytest_AN
BUILD/mytest_AY
BUILD/mytest_AN
BUILD/mytest_AY: CXXFLAGS+=-DOPTION_A
BUILD/mytest_AY: mytest.cpp
$(CXX) $(CXXFLAGS) -o $@ $< $(LDFLAGS)
BUILD/mytest_AN: mytest.cpp
$(CXX) $(CXXFLAGS) -o $@ $< $(LDFLAGS)
This is fine.
But now, if I have 2 options to test (say "A" and "B"), you see the point:
I will have 4 targets to build and run:
test: BUILD/mytest_AYBY BUILD/mytest_ANBY BUILD/mytest_AYBN BUILD/mytest_ANBN
BUILD/mytest_AYBY
BUILD/mytest_ANBY
BUILD/mytest_AYBN
BUILD/mytest_ANBN
BUILD/mytest_AYBN: CXXFLAGS+=-DOPTION_A
BUILD/mytest_AYBY: CXXFLAGS+="-DOPTION_A -DOPTION_B"
BUILD/mytest_ANBY: CXXFLAGS+=-DOPTION_B
BUILD/mytest_AYBY: mytest.cpp
$(CXX) $(CFLAGS) -o $@ $< $(LDFLAGS)
BUILD/mytest_ANBY: mytest.cpp
$(CXX) $(CFLAGS) -o $@ $< $(LDFLAGS)
BUILD/mytest_AYBN: mytest.cpp
$(CXX) $(CFLAGS) -o $@ $< $(LDFLAGS)
BUILD/mytest_ANBN: mytest.cpp
$(CXX) $(CFLAGS) -o $@ $< $(LDFLAGS)
I have two questions:
is there a way to have a single rule/recipe instead of the four?
There are all the same, except for the target name.
this approach, while ok for 1 or 2 build-time options, does not scale well.
3 would already be pretty much cumbersome, more, it becomes a nightmare.
How would you handle that situation?
| Interesting problem. If you have GNU make you can try something like the following. The compilation and execution commands are just echoed; remove the two echo and the @ silencers when you will be satisfied with what you see. There are 3 options: A, B and C; add more if you wish or specify them on the command line with make test ONAMES="A B C D E F".
# option names
ONAMES := A B C
# number of options
ONUM := $(words $(ONAMES))
# configuration binary strings (e.g., 000 001 ... 111)
CONFIGS := $(shell echo "obase=2; for(i=0; i<2^$(ONUM); i++) 2^$(ONUM)+i" | \
bc | sed 's/1//')
# one space
SPACE := $(NULL) $(NULL)
# list of all test binaries
TESTBINS :=
# the macro used to instantiate a test
# $(1): the configuration binary string (e.g. 101)
define TEST_macro
# the configuration list in NAMEY/N format (e.g., AY BN CY)
config-$(1) := $$(join $(ONAMES),$$(subst 1,Y ,$$(subst 0,N ,$(1))))
# the test binary (e.g., BUILD/mytest_AYBNCY)
test-$(1) := BUILD/mytest_$$(subst $$(SPACE),,$$(config-$(1)))
# the list of active options (e.g., A C)
options-$(1) := $$(subst Y,,$$(filter %Y,$$(config-$(1))))
# add the test binary to list of all test binaries
TESTBINS += $$(test-$(1))
# target-specific compilation options
$$(test-$(1)): CXXFLAGS += $$(addprefix -DOPTION_,$$(options-$(1)))
endef
# apply macro on each configuration binary string
$(foreach c,$(CONFIGS),$(eval $(call TEST_macro,$(c))))
# one phony target per test run (e.g., BUILD/mytest_AYBNCY.run)
TESTRUNS := $(addsuffix .run,$(TESTBINS))
.PHONY: $(TESTRUNS)
# one phony target for all test runs
.PHONY: test
test: $(TESTRUNS)
# static pattern rule for the test runs
$(TESTRUNS): %.run: %
@echo "./$<"
# rule for the test binaries
$(TESTBINS): mytest.cpp
@echo "$(CXX) $(CXXFLAGS) -o $@ $< $(LDFLAGS)"
Demo:
$ make test
g++ -o BUILD/mytest_ANBNCN mytest.cpp
g++ -DOPTION_C -o BUILD/mytest_ANBNCY mytest.cpp
g++ -DOPTION_B -o BUILD/mytest_ANBYCN mytest.cpp
g++ -DOPTION_B -DOPTION_C -o BUILD/mytest_ANBYCY mytest.cpp
g++ -DOPTION_A -o BUILD/mytest_AYBNCN mytest.cpp
g++ -DOPTION_A -DOPTION_C -o BUILD/mytest_AYBNCY mytest.cpp
g++ -DOPTION_A -DOPTION_B -o BUILD/mytest_AYBYCN mytest.cpp
g++ -DOPTION_A -DOPTION_B -DOPTION_C -o BUILD/mytest_AYBYCY mytest.cpp
./BUILD/mytest_ANBNCN
./BUILD/mytest_ANBNCY
./BUILD/mytest_ANBYCN
./BUILD/mytest_ANBYCY
./BUILD/mytest_AYBNCN
./BUILD/mytest_AYBNCY
./BUILD/mytest_AYBYCN
./BUILD/mytest_AYBYCY
Explanations:
We first generate the 2^3=8 binary strings from 000 to 111 with, e.g., bc thanks to the shell make function. We assign the result to the make variable CONFIGS. These binary strings correspond to all possible configurations of the 3 options where a 1 means yes (Y) and 0 means no (N).
Then, we process each of these configuration strings with the TEST_macro macro. This is where the foreach-eval-call construct enters the picture. With a mixture of join, subst and other make functions we transform each binary string. For instance, 101 is first transformed into the AY BN CY list (variable config-101), next into the BUILD/mytest_AYBNCY test binary name (variable test-101) and next into the A C list of enabled options (variable options-101). Finally, the list of enabled options is in turn transformed into a target-specific CXXFLAGS value with addprefix.
Note: having one separate phony target per test run (e.g., BUILD/mytest_AYBNCY.run) is interesting if you have a multi-core computer and you want to run N tests in parallel with make -jN.
Note: all this is rather simple except one specific aspect: the macro is expanded twice by make. Once as parameter of the eval function and once more when the resulting make construct is re-parsed by make. This is why we use $$ almost everywhere we would normally find just $: to escape the first expansion.
|
70,334,243 | 70,334,616 | Template class definition | Does a class template -that takes integer parameter- define multiple classes for different integer inputs?
for ex:
I applied the following code
template<int val>
class MyClass
{
public:
static int var;
};
template<int val> int MyClass<val>::var = val;
int main(int argc, char* argv[])
{
MyClass<5> a;
MyClass<7> b;
MyClass<9> c;
std::cout << a.var << " , " << b.var << " , " << c.var << std::endl;
return 0;
}
Output
5 , 7 , 9
does it mean that a class definition is created for every integer passed as template argument (as the static member variable is different every time) ?
Is there a way to check the generated class definitions? I tried to check map file and assembly code but no luck
| Yes, these will be 3 distinct types
You can for instance use C++ Insights to get an idea of the code that the compiler generates from class templates.
#include <iostream>
template<int val>
class MyClass
{
public:
static int var;
};
/* First instantiated from: insights.cpp:14 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class MyClass<5>
{
public:
static int var;
// inline constexpr MyClass() noexcept = default;
};
#endif
/* First instantiated from: insights.cpp:15 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class MyClass<7>
{
public:
static int var;
// inline constexpr MyClass() noexcept = default;
};
#endif
/* First instantiated from: insights.cpp:16 */
#ifdef INSIGHTS_USE_TEMPLATE
template<>
class MyClass<9>
{
public:
static int var;
// inline constexpr MyClass() noexcept = default;
};
#endiint MyClass<9>::var = 9;
int main(int argc, char ** argv)
{
MyClass<5> a = MyClass<5>();
MyClass<7> b = MyClass<7>();
MyClass<9> c = MyClass<9>();
std::operator<<(std::operator<<(std::cout.operator<<(a.var), " , ").operator<<(b.var), " , ").operator<<(c.var).operator<<(std::endl);
return 0;
}
edit: Altough you see CppInsight is not perfect, as it screwed up the instantiation of the static member variables.
|
70,334,799 | 70,335,523 | Taking the address of a non-instantiated struct | I am reading "C++ Templates. The Complete Guide. Second Edition", by David Vandevoorde, Nicolai M. Josuttis, Douglas Gregor. And, there is something that I don't understand.
This is one code example in pg. 59:
// define binary tree structure and traverse helpers:
struct Node {
int value;
Node* left;
Node* right;
Node(int i=0) : value(i), left(nullptr), right(nullptr) {}
// ...
};
auto left = &Node::left;
auto right = &Node::right;
// traverse tree, using fold expression:
template<typename T, typename... TP>
Node* traverse (T np, TP... paths) {
return (np ->* ... ->* paths);
}
// np ->* paths1 ->* paths2 ...
int main()
{
// init binary tree structure:
Node* root = new Node{0};
root->left = new Node{1};
root->left->right = new Node{2};
// ...
// traverse binary tree:
Node* node = traverse(root, left, right);
//...
}
What I don't understand is:
auto left = &Node::left;
auto right = &Node::right;
These are global variables of type (according to the llvm compiler): Node *Node::*. With value, for example the first one, left: &Node::left
The question is, being the variable left a pointer, how can I take the address (operator&) of a non-instantiated struct?
| This is not an "a non-instantiated struct".
This is an address of a class member.
left is a member of the Node class. This takes its "address", and not the actual address of some instance of some Node class. This does not take the left pointer of some particular class instance, but of the left itself.
The address of a class member cannot be used just like that, by itself, but requires a specific instance of the class.
auto member_address = &Node::left;
// ...
Node *p;
// ...
Node *ptr=p->*member_address;
Whatever p is, this fetches p's left. If member_address was &Node::right, ptr gets set to p->right.
|
70,335,313 | 70,335,498 | How to test a class with google test? | I'm just learning google test, I have a class and I want to test its member function, below is the demo code:
class B {
//......
};
class A {
public:
//.....
void add (string s, B* ptrb) { m.insert(s, ptrb); }
void remove(string s) {
auto it = m.find(s);
if (it != m.end())
m.erase(it);
}
B* operator[](string s)
{
auto it = m.find(s);
if (it != m.end())
return (*it).second;
}
//.....
protected:
map<B*> m;
//.....
}
if I want to test add like this:
class mygtest : public ::testing::Test
{
protected:
//....setup
//....teardown
A a;
};
TEST_F(mygtest, testadd)
{
B b1;
B b2;
a.add("1", &b1);
a.add("2", &b2);
//...how should i do next?
EXPECT_EQ(.....) //compare with who?
}
this is the first question.
the second question is:
In some conditions , I have to call another member function to get a value first , and use EXPECT_EQ to test the current member function, how to test a function without using other member funtion? if it's necessary ?
| You have to just verify that state of A has changed as desired.
So just check if it contains added objects.
TEST_F(mygtest, testadd)
{
B b1;
B b2;
a.add("1", &b1);
a.add("2", &b2);
EXPECT_EQ(a["1"], &b1);
EXPECT_EQ(a["2"], &b2);
EXPECT_EQ(a["3"], nullptr);
}
https://godbolt.org/z/ezrjdY6hh
Since there is not enough context it is impossible o improve this test (it doesn't look nice).
You can't avoid use of different functions. You are testing behavior of a class. So you are verify that other function do something else after state has been changed.
Do not event think to friend a test with production class. This is bad practice, since this will entangle test with implementation details. You will no be able refactor production code when test check implementation detail.
Here is small refactoring of test I usually do to improve how easy test is maintained: https://godbolt.org/z/Tc1n9Evzs
|
70,335,429 | 70,335,753 | How many translation units in one module? | Does a module with multiple source files (.cpp) have one or multiple translation units? My understanding is that every single source file (.cpp) will be its own translation unit unless it is included, and #pragma onced (which I guess is a malpractice), but I don't know how that is done in a modular program. If there's any difference, then I am particularly interested in Visual Studio C++ development (post C++2020)
| A module consists of one or more translation units. A translation unit that starts with a module declaration is termed a module unit, and if there are multiple module units in a program that have the same module name (ignoring any module partition) then they belong to the same module.
|
70,335,947 | 70,336,048 | How a multiple times #included guarded header file will be inside different translation units? | I know that #inclusion is often described as a text copy-pasting preprocessor directive. Now if a header is #include guarded, or #pragma onced, then how'd we describe what is actually happening past the first translation unit to #include said header?
| There is no "first" translation unit. All translation units are conceptually translated in parallel (of course, in practice you might end up compiling them one at a time, but it doesn't matter).
Each translation unit begins with a blank slate. Technically that isn't quite true because you can add #defines at the command line and there are some predefined macros as well, but anyway, no translation unit will have a "memory" of #defines that were executed in any other translation unit. Thus, a header may be #included multiple times despite the guards. It is just that it won't be #included multiple times into a single translation unit.
This means that you must still take care to avoid multiple definitions: for example, if your header contains a global variable then you must ensure it is const (so it will have internal linkage) or explicitly declare it inline (to collapse all definitions into one) or extern (to suppress definition in the header so you can place the definition into a single translation unit).
Despite the fact that include guards don't prevent multiple definitions across multiple translation units, they do prevent multiple definitions within a single translation unit, and this is important because even though some entities may be defined multiple times in a program, it's still not allowed for multiple definitions to appear in the same translation unit. For example, if you have an inline global variable in a header, then multiple translation units can include that header and the definitions will all be collapsed into a single definition at link time, but you will get a compilation error if any one translation unit defines that variable multiple times. Therefore, such a header must have an include guard.
|
70,336,171 | 70,338,064 | ctypes: How to access array of structure returned by function? | I have a c++ API functions which I need to call from python using ctypes.
In my c++ libamo.h, I have prototypes for struct and function as below,
typedef struct contain_t
{
uint8_t id;
uint16_t ele1;
uint16_t ele2;
uint16_t ele3;
uint16_t ele4;
float ele5;
} mycontain;
mycontain* get_result(void *context, int r, int c, unsigned char* rawdata);
In my c++ libamo.cpp,
I have declared global array of struct,
mycontain all_contain[50];
and the function mycontain* get_result() populates array of struct, which I have tested in c++ by printing the contents of struct.
In ctypes:
am loading the libamo.so.
defined the structure template as,
from ctypes import *
class mycontain(Structure):
_fields_ = [('id', c_uint),
('ele1',c_uint),
('ele2', c_uint),
('ele3', c_uint),
('ele4', c_uint),
('ele5', c_float) ]
ptr_cnt = POINTER(mycontain)
amo_get_result = libamo.get_result
amo_get_result.restype = ptr_cnt
amo_get_result.argtypeps = [c_void_p, c_int, c_int, c_char_p]
res = amo_get_result(amo_context, 300, 300, raw_val.ctypes.data_as(c_char_p))
I tried following method to get the data from member of struct.
Method 1:
output_res = res.contents
print(output_res.id, output_res.ele1, output_res.ele2, output_res.ele3, output_res.ele4, output_res.ele5)
at output I get, for above elements
7208960 0.0 4128919 173 1049669215 21364736
Method 2: Tried casting
print(cast(output_res.id, POINTER(c_uint)))
output>><__main__.LP_c_uint object at 0x7f9450f3c0>
My question is,
- How to elegantly read data from array of struct. I have refereed multiple SO posts, most discusses ways to access single instance of struct, not array of structs.
| Use the matching types in the struct. c_uint is typically 32-bit so your Python structure has the wrong size.
To access the array, index the pointer (e.g. output_res[0].id) or use slicing.
Here's a reproducible example with a test DLL:
test.cpp
#include <stdint.h>
#ifdef _WIN32
# define API __declspec(dllexport)
#else
# define API
#endif
typedef struct contain_t
{
uint8_t id;
uint16_t ele1;
uint16_t ele2;
uint16_t ele3;
uint16_t ele4;
float ele5;
} mycontain;
mycontain all_contain[5];
extern "C"
API mycontain* get_result(void *context, int r, int c, unsigned char* rawdata) {
for(int i = 0; i < 50; ++i) {
all_contain[i].id = i;
all_contain[i].ele1 = i*2;
all_contain[i].ele2 = i*3;
all_contain[i].ele3 = i*4;
all_contain[i].ele4 = i*5;
all_contain[i].ele5 = i * 1.01;
}
return all_contain;
}
test.py
from ctypes import *
class mycontain(Structure):
_fields_ = [('id', c_uint8), # use correct types
('ele1',c_uint16),
('ele2', c_uint16),
('ele3', c_uint16),
('ele4', c_uint16),
('ele5', c_float) ]
# Make a display representation for easy viewing
def __repr__(self):
return f'mycontain(id={self.id}, ele1={self.ele1}, ..., ele5={self.ele5:.2f})'
dll = CDLL('./test')
dll.get_result.argtypes = c_void_p, c_int, c_int, c_char_p
dll.get_result.restype = POINTER(mycontain)
res = dll.get_result(None, 300, 300, None)
print(res[:5]) # slice to appropriate size to get list of elements
Output:
[mycontain(id=0, ele1=0, ..., ele5=0.00), mycontain(id=1, ele1=2, ..., ele5=1.01), mycontain(id=2, ele1=4, ..., ele5=2.02), mycontain(id=3, ele1=6, ..., ele5=3.03), mycontain(id=4, ele1=8, ..., ele5=4.04)]
|
70,336,239 | 70,336,267 | Using vectors in C++ program is not printing anything | I have written a C++ program to find fibonacci numbers. It's running successfully but is not printing anything.
#include<bits/stdc++.h>
using namespace std;
int main(){
int n = 5;
vector<int> fib;
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++){
fib[i] = fib[i-1] + fib[i-2];
}
cout<<fib[n];
}
If I do the same thing using array instead of vector it prints successfully.
#include<bits/stdc++.h>
using namespace std;
int main(){
int n = 5;
int fib[10];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++){
fib[i] = fib[i-1] + fib[i-2];
}
cout<<fib[n];
}
I have tested this on sublime text and onlinegdb.
| int fib[10];
This creates an array of 10 integers.
vector<int> fib;
This creates a vector of size 0, with 0 integers.
For these two snippets to match, you need to initialize the vector with 10 integers like the array. So:
vector<int> fib(10);
Some notes on vectors
One of the big differences between std::vector and primitive arrays is that std::vector is resizable! So while initializing the vector with 10 ints like above will work, you could also add them on the fly using push_back() or by calling resize().
Likewise, std::vector has a .at() function for access. It's marginally slower than the subscript operator ([]), so I would not suggest using it in production-level code. But while you're learning, I would strongly suggest using .at(), as it will do bounds checking for you. So this program would've told you you were trying to access locations in the vector that don't exist--instead of just running with Undefined Behavior.
|
70,336,370 | 70,336,563 | Initialized declarator inside of C++ catch statement | Do you think that the initialized declarator is a valid lexical structure inside of the caught-declaration part of the catch statement? For example, take a look at the following code:
void func( int = 1 )
{
try
{
}
catch( int a = 1 )
{
}
}
It compiles fine under latest MSVC 17.0.2 but fails to compile under latest GCC 11.2 (tested using Godbolt.org). I want to know the answer to form a purely lexical understanding about the correct typing of C++ code.
If you read this cppreference.com article then you find that it says that the declaration should be exactly the same as(*) for function signature arguments, thus putting legitimacy into the MSVC C++ lexer.
* It's not actually the same. The text just happens to distinguish between just a declarator and the initializer part being separate.
| No. It's invalid.
The grammar for the catch clause specifies type-specifier-seq declarator. The declarator part of that does not include an initializer. Compare this with the grammar for a function parameter, which does allow an initializer:
attr(optional) decl-specifier-seq declarator = initializer
|
70,336,422 | 70,341,420 | Bluetooth Low Energy application in Visual Studio C++ for image sharing. Which tools should I use? | I'm trying to develop a C++ application on Windows 10 (using Visual Studio 2017) capable of looking for nearby mobile devices and sending data (images) via Bluetooth. I'm new to Bluetooth applications, but from what I understand, the best solution is to use BLE and make the computer a GATT server.
For this purpose, I'm quite confused about which tool I should use in order to start creating my application, since most of the libraries I have found online are outdated or poorly documented (libblepp, gattlibpp, bluetoe).
I've also found this Windows API but I don't understand if this is what I should use and I don't know how to include it in my project neither.
Has anybody had some experience with this and could provide me some hints concerning the right tool to use, in order to get started with my project?
On the other side, I would like to develop a mobile app using Flutter capable of receiving the image and reading the data sent by the computer. flutter_blue looks like the best option to go with.
Edit: The idea for the application is the following: the computer runs an application that generates various frames. In the meanwhile, it constantly scans for nearby devices and, whenever a user makes a request, it sends the current output image to the device that makes the request.
| The Windows API is what you should use if you write a C++ application for Windows. That will be the best supported option. If you happen to find some library that also does BLE it will probably just be a wrapper around the Windows API.
Unfortunately these APIs use the WinRT architecture which is not the easiest to set up but should work fine once you've managed to set up the environment.
|
70,337,566 | 70,337,711 | How does std::unique_ptr handle raw pointers/references in a class? | Let's say I have a class A with the following definition:
class A {
A(std::string& s) : text_(s) {}
private:
std::string& text;
}
Note that A contains a reference to a string object. This can be because we don't want to copy or move the object.
Now, if I have the following code
std::string text = "......";
std::unique_ptr<A>(new A(text));
// now I destroy text in some way, either explicitly call the deconstructor or it goes out of scope somehow
The question is what happens now to the unique_ptr's object A? The A contained a reference to the object text which is deleted. Does unique_ptr's A have now a dangling pointer? Or does unique_ptr handle this case and extend the lifetime of the object for which it contains a raw pointer?
| C++ is not a safe language. If you have a pointer or reference to an object that is destroyed, using that pointer or reference is a bug.
Assuming you actually construct an A that outlives text, it will still reference the destroyed object, and any use of that member is undefined behaviour.
|
70,338,242 | 70,347,271 | avoiding impossible cases in macro | consider the following macro:
#define checkExists(map, it, value) {\
it = map.find(value);\
if(it == map.end()){\
if(!strcmp(typeid(value).name(), "Ss")){ /* value is an std::string */\
manageError(ERR_CANT_FIND_RESSOURCES, "in %s __ failed to find %s in map %s", __FUNCTION__, value.c_str(), #map);\
\
}else if(!(strcmp(typeid(value).name(), "Pc") * strcmp(typeid(value).name(), "PKc"))){ /* value is either char* or const char* */\
manageError(ERR_CANT_FIND_RESSOURCES, "in %s __ failed to find %s in map %s", __FUNCTION__, value #map); /* problem here because for gcc value could be an std::string */ \
\
} else \
manageError(ERR_CANT_FIND_RESSOURCES, "in %s __ failed to find 0x%04X in map %s", __FUNCTION__, value #map); /* problem here because for gcc value could be an std::string */\
}\
}
manageError is a also a macro that calls a function logWarning which only accepts only fundamental types (eg int, char* ...). The prototypes are:
#define manageError(error_code, error_str, ...) {\
{\
logWarning(error_str, ##__VA_ARGS__);\
return error_code;\
}\
}
int logWarning(const char* printf_format, ...);
So if my value is an std::string, I am giving manageError a const char *.
It's seems like checkExists isn't evaluated compile time... so gcc being very clever, it doesn't allow me the last two manageError calls, because it sees value as an std::string or it's impossible because std::string is only possible in the first case.
For example, this doesn't work:
std::string foo;
checkExists(myMap, myMapIterator, foo);
gcc output:
error: cannot pass objects of non-trivially-copyable type 'const string {aka const struct std::basic_string<char>}' through '...'
Do you know how I can solve this issue ?
Edit
the idea of that mecanism is to be able to leave the current function if an error occured. For example:
int func(){
std::string foo;
checkExists(myMap, myMapIterator, foo); //leaves the function if foo is not found inside myMap
return 0;
}
so I have to use macro to be able to leave the function (not possible for me to use templates).
| I solved the problem by converting value to std::string no matter the input type.
#define checkExists(map, it, value) {\
it = map.find(value);\
if(it == map.end()){\
std::stringstream tmpSs;\
if(!(strcmp(typeid(value).name(), "Pc") * strcmp(typeid(value).name(), "PKc") * strcmp(typeid(value).name(), "Ss"))){\
tmpSs << value;\
}else{\
tmpSs << "0x" << std::uppercase << std::setfill('0') << std::setw(4) << std::hex << value; /* converting value to hex format */\
}\
\
manageError(ERRCAN_T_FIND_RESSOURCES, "in %s __ failed to find %s in map %s", __FUNCTION__, tmpSs.str().c_str(), #map);\
}\
}
|
70,338,351 | 70,338,689 | What is wrong with this constructor definition? | I want to write a class of "Clock", which basically holds hours, minutes and seconds (as integers).
I want that by default the constructor would initalize hours,minutes and seconds to 0 unless other input was given. So I declared the following:
Clock(int hour=0, int minute=0, int second=0);
Which basically should give me 4 different constructors - the first one is the default constructor, and then a constructor which recieves hours as an input, a constructor which recievrs hours and minutes as an input, and a constructor which recieves all 3 as an input.
Next, I want the constructor to initalize the fields only if the input is valid, meaning, hours should be between 0 to 24, minutes and seconds should be between 0 to 60. So I wrote 3 functions that checks if the input is legal, and then I implemented the constructor as the following:
Clock::Clock(int hour , int minute, int second ){
if (isHourLegal(hour) && isMinLegal(minute) && isSecLegal(second)){
time[0] = hour; time[1] = minute; time[2] =second;
}
else
Clock();
}
Where time[] is an array of length tree which holds the hours,minutes and seconds fields of the object.
Basially, if one of the inputs is wrong, Im calling Clock(); which should create an object with the default intefers I wrote when I declared.
Is there something wrong with the way I implemented the constructor? Im having unexpected outputs when I try to print an object fields.
Also,
Assume I fixed my constructor to:
Clock::Clock(int hour , int minute, int second ){
if (isHourLegal(hour) && isMinLegal(minute) && isSecLegal(second)){
time[0] = hour; time[1] = minute; time[2] =second;
}
else
time[0] = 0; time[1] = 0; time[2] =0;
}
}
Im trying to call the default constructor in my main function by :
Clock clock1();
clock1.printTime();
(printTime is a method which prints the fields).
But I get an error. Is there a porblem using the constructor this way?
| You can solve this easily.
If you have default arguments, chances are these will pass the test (you define them, after all :-)). So why don't take advantage of this and just write a single constructor that handles both cases?
In both cases (i.e. with/without passing arguments to it), the checks will be performed and on success a valid Clock will be constructed. For your default arguments, this will be trivially true. In the failure case, your constructor will throw and you won't be having a half-initialized/broken object roaming around.
Maybe the point which you are missing is: If the time format is not legal, you should usually throw.
Look at the following definition, which should be sufficient for your case.
// Declaration
Clock(int hour=0, int minute=0, int second=0);
// ...
// Definition
Clock::Clock(int hour, int minute, int second)
: time { hour, minute, second } // assuming int time[3]; here
{
if (!isHourLegal(hour) || !isMinLegal(minute) || !isSecLegal(second)){
throw std::invalid_argument("Illegal time format!");
}
}
|
70,338,886 | 70,339,052 | How to use the user input for a file name? | I'm pretty new in c++. I've testing a small program which takes the user input and create a file which contains the data dependent on the user input. So every time I've to change the name of file before running the code. Are there methods to use the user input as file name?
std::cout << "Enter the block size: ";
int block_size = 0;
std::cin >> block_size;
std::ofstream f;
f.open("#CAN YOU ASSIGN ME AS NAME SAME AS USER INPUT! PLEASSSEE#");
| Perhaps this works?
std::cout << "Enter the block size: ";
int block_size = 0;
std::cin >> block_size;
std::cout << "Enter the file name: ";
std::ws(std::cin);
std::string filename;
std::getline(std::cin, filename);
std::ofstream f;
f.open(filename);
std::ws will eat the newline after the block size, otherwise std::getline() returns immediately:
Why does std::getline() skip input after a formatted extraction?
|
70,338,946 | 70,339,902 | GL_TEXTUREn+1 activated and bound instead of GL_TEXTUREn on Apple Silicon M1 (possible bug) | Let's first acknowledge that OpenGL is deprecated by Apple, that the last supported version is 4.1 and that that's a shame but hey, we've got to move forward somehow and Vulkan is the way :trollface: Now that that's out of our systems, let's have a look at this weird bug I found. And let me be clear that I am running this on an Apple Silicon M1, late 2020 MacBook Pro with macOS 11.6. Let's proceed.
I've been following LearnOpenGL and I have published my WiP right here to track my progress. All good until I got to textures. Using one texture was easy enough so I went straight into using more than one, and that's when I got into trouble. As I understand it, the workflow is more or less
load pixel data in a byte array called textureData, plus extra info
glGenTextures(1, &textureID)
glBindTexture(GL_TEXTURE_2D, textureID)
set parameters at will
glTexImage2D(GL_TEXTURE_2D, ... , textureData)
glGenerateMipmap(GL_TEXTURE_2D) (although this may be optional)
which is what I do around here, and then
glUniform1i(glGetUniformLocation(ID, "textureSampler"), textureID)
rinse and repeat for the other texture
and then, in the drawing loop, I should have the following:
glUseProgram(shaderID)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, textureID)
glActiveTexture(GL_TEXTURE1)
glBindTexture(GL_TEXTURE_2D, otherTextureID)
I then prepare my fancy fragment shader as follows:
#version 410 core
out vec4 FragColor;
in vec2 TexCoord;
uniform sampler2D textureSampler;
uniform sampler2D otherTextureSampler;
void main() {
if (TexCoord.x < 0.5) {
FragColor = texture(textureSampler, TexCoord);
} else {
FragColor = texture(otherTextureSampler, TexCoord);
}
}
and I should have a quad on screen with a texture made up by textureSampler on its left half, and otherTextureSampler on its right half. Instead, I have otherTextureSampler on the left half, black on the other half, and a log message that says
UNSUPPORTED (log once): POSSIBLE ISSUE: unit 1 GLD_TEXTURE_INDEX_2D is unloadable and bound to sampler type (Float) - using zero texture because texture unloadable
I've been on this bug's trail for two days now and there just isn't very much on the Internet. Some reports point to a possible bug in Apple's GLSL compiler, some others point to the need for binding an extra texture for no apparent reason. These three are the most relevant pieces of information I managed to find:
https://blog.dengine.net/2021/01/wonders-and-mysteries-of-the-m1/
https://bugreports.qt.io/browse/QTBUG-89803
https://bugreports.qt.io/browse/QTBUG-97981
However, none of these helped me very much. Until I did something without thinking. The eagle-eyed among you will have noticed that the drawing code in my git repo is slightly different. It says right here that I am in fact using GL_TEXTURE1 and GL_TEXTURE2.
It was my understanding that 0 and 1 were the two texture units that I was activating and binding, so why does using texture units 1 and 2 yield the expected result?
I tried to add calls to glActiveTexture(GL_TEXTURE0) and 1 right after generating the textures and before binding them, but with zero success. I also tried using a sampler array like this person suggests and going in with a bunch of ifs and integer indices, but of course I was still getting the wrong result.
I spent a few hours trying every possible combination and the only practical "solution" is to use "+1" texture units, as in GL_TEXTUREn with n >= 1.
Question: with all the caveat expressed in the very first paragraph, who is doing something wrong here? Is it noob me who's trying to learn decades old technology on modern hardware, or is it genuinely a bug in Apple's implementation of OpenGL or the GLSL compiler, and so there's zero chance of having it fixed and I should just get on with my "special hardware manufacturer's" crutches?
| Instead of passing a texture handle to glUniform1i(glGetUniformLocation(ID, "textureSampler"), ...), you need to pass a texture slot index.
E.g. if you did glActiveTexture(GL_TEXTUREn) before binding the texture, pass n.
|
70,339,167 | 70,341,062 | pybind11 conflict with GetModuleFileName | I am using pybind11 to let python call an existing C++ module (library). The connection is through, however, in the C++ library, ::GetModuleFileName (Visual Studio) is called to to determine the physical path of the loaded module as it is run in C++. But when I call the library from python (Jupyter Notebook) through pybind11, the physical path of python.exe is returned. How can I configure or change to make sure the physical path of the C++ library is obtained?
The C++ code is like this:
Lib.h
#pragma once
void run();
Lib.cpp
#include <fstream>
#include <stdexcept>
#include <windows.h>
#include "libloaderapi.h"
#include "Lib.h"
void run()
{
char buf[1024];
::GetModuleFileName(0, buf, sizeof(buf));
std::ofstream of;
of.open("logging.txt");
if (!of.is_open()) {
throw std::runtime_error("Cannot open logging.txt");
}
of << "The loaded module is " << buf << std::endl;
}
The pybind11 interface code:
Direct.cpp
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "Lib.h"
namespace py = pybind11;
// wrap c++ function
void wrapper() {
run();
}
PYBIND11_MODULE(run_app, m) {
// optional module docstring
m.doc() = "pybind11 plugin";
m.def("run", &wrapper, "Run C++ Application");
}
The pybind11 setup file:
setup.py
#from distutils.core import setup, Extension
#from distutils import sysconfig
from setuptools import setup, Extension
import pybind11
# The following is for GCC compiler only.
#cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
cpp_args = []
sfc_module = Extension(
'run_app',
sources=['Direct.cpp',
'Lib.cpp'],
include_dirs=[pybind11.get_include(), '.'],
language='c++',
extra_compile_args=cpp_args,
)
setup(
name='run_app',
version='1.0',
description='Python package with RunApp C++ extension (PyBind11)',
ext_modules=[sfc_module],
)
To build:
python setup.py build
The python code calling this library:
py_run_app.py
import os
import sys
sys.path.append(os.path.realpath('build\lib.win-amd64-3.7'))
from run_app import run
run()
After the run:
python py_run_app.py
In the logging.txt
The loaded module is C:....\python.exe
What I want to see is the physical location of the module.
| "Module" in Windows parlance is a DLL or an executable file loaded to be a part of a process. Each module has a module handle; by convention, the special handle NULL signifies the executable file used to create the process.
GetModuleFileName requires module handle as the first argument. You pass 0, you get back the name of the module with the special handle NULL, i.e. the executable. This is fully expected.
In order to get the file name of a DLL, you need to find out what its handle is. You can find the handle of the current module:
HMODULE handle;
static char local;
bool ok = GetModuleHandleEx (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCSTR)&local,
&handle);
local can be any function or static/extern variable in the current module. ref.
|
70,339,753 | 70,354,210 | What is XlaBuilder for? | What's the XLA class XlaBuilder for? The docs describe its interface but don't provide a motivation.
The presentation in the docs, and indeed the comment above XlaBuilder in the source code
// A convenient interface for building up computations.
suggests it's no more than a utility. However, this doesn't appear to explain its behaviour in other places. For example, we can construct an XlaOp with an XlaBuilder via e.g.
XlaOp ConstantLiteral(XlaBuilder* builder, const LiteralSlice& literal);
Here, it's not clear to me what role builder plays (note functions for constructing XlaOps aren't documented on the published docs). Further, when I add two XlaOps (with + or Add) it appears the ops must be constructed with the same builder, else I see
F tensorflow/core/platform/statusor.cc:33] Attempting to fetch value instead of handling error Invalid argument: No XlaOp with handle -1
Indeed, XlaOp retains a handle for an XlaBuilder. This suggests to me that the XlaBuilder has a more fundamental significance.
Beyond the title question, is there a use case for using multiple XlaBuilders, or would you typically use one global instance for everything?
| XlaBuilder is the C++ API for building up XLA computations -- conceptually this is like building up a function, full of various operations, that you could execute over and over again on different input data.
Some background, XLA serves as an abstraction layer for creating executable blobs that run on various target accelerators (CPU, GPU, TPU, IPU, ...), conceptually kind of an "accelerator virtual machine" with conceptual similarities to earlier systems like PeakStream or the line of work that led to ArBB.
The XlaBuilder is a way to enqueue operations into a "computation" (similar to a function) that you want to run against the various set of accelerators that XLA can target. The operations at this level are often referred to as "High Level Operations" (HLOs).
The returned XlaOp represents the result of the operation you've just enqueued. (Aside/nerdery: this is a classic technique used in "builder" APIs that represent the program in "Static Single Assignment" form under the hood, the operation itself and the result of the operation can be unified as one concept!)
XLA computations are very similar to functions, so you can think of what you're doing with an XlaBuilder like building up a function. (Aside: they're called "computations" because they do a little bit more than a straightforward function -- conceptually they are coroutines that can talk to an external "host" world and also talk to each other via networking facilities.)
So the fact XlaOps can't be used across XlaBuilders may make more sense with that context -- in the same way that when building up a function you can't grab intermediate results in the internals of other functions, you have to compose them with function calls / parameters. In XlaBuilder you can Call another built computation, which is a reason you might use multiple builders.
As you note, you can choose to inline everything into one "mega builder", but often programs are structured as functions that get composed together, and ultimately get called from a few different "entry points". XLA currently aggressively specializes for the entry points it sees API users using, but this is a design artifact similar to inlining decisions, XLA can conceptually reuse computations built up / invoked from multiple callers if it thought that was the right thing to do. Usually it's most natural to enqueue things into XLA however is convenient for your description from the "outside world", and allow XLA to inline and aggressively specialize the "entry point" computations you've built up as you execute them, in Just-in-Time compilation fashion.
|
70,339,767 | 70,339,932 | My code with regular expressions for file doesn't run properly | #include <iostream>
#include <fstream>
#include <string>
#include <regex>
using namespace std;
int main()
{
regex r1("(.*\\blecture\\b.*)");
regex r2("(.* practice.*)");
regex r3("(.* laboratory practice.*)");
smatch base_match;
int lecture = 0;
int prakt = 0;
int lab = 0;
string name = "schedule.txt";
ifstream fin;
fin.open(name);
if (!fin.is_open()) {
cout << "didint open ";
}
else {
string str;
while (!fin.eof()) {
str = "";
getline(fin, str);
cout << str << endl;
if (regex_match(str, base_match, r1)) {
lecture++;
}
if (regex_match(str, base_match, r2)) {
prakt++;
}
if (regex_match(str, base_match, r3)) {
lab++;
}
}
}
cout << "The number of lectures: " << lecture << "\n";
cout << "The number of practices: " << prakt << "\n";
cout << "[The number of laboratory work][1]: " << lab << "\n";
fin.close();
}
In this program, I need to count the number of lectures, practice and laboratory work per week using regular expressions. I have got a text file, which you can see on the screen. But for lectures and practice, it doesn't work right.
enter image description here
| You need the number of times each regex matches. C++ has std::sregex_iterator for performing multiple regex matches over a string.
That means you can do the following:
for (auto it = std::sregex_iterator{str.cbegin(), str.cend(), r1}; it != std::sregex_iterator{}; it++) {
lecture++;
}
If you want to get really fancy you can even do it in one go:
auto it = std::sregex_iterator{str.cbegin(), str.cend(), r1};
lecture += std::distance(it, std::sregex_iterator{});
Alternatively, you can call std::regex_search several times, starting from the end offset of the previous match (or 0 for the first).
EDIT: as remarked in the comments, this assumes that your regexes are suitable to incremental matching. Yours eat the whole string (presumably because regex_match is anchored whereas regex_search/regex_iterator are not), so you need to at least change your regular expression definitions to the following:
regex r1("\\blecture\\b");
regex r2(" practice");
regex r3(" laboratory practice");
... and of course every match for r3 is also a match for r2, but I leave that for you.
|
70,340,224 | 70,340,299 | I'm not sure what to do to have the expected output | This is My Code
for(int y=1;y<=20;y++)
{
for(int z=1;z<=y;z++)
{
cout<<z;
z++;
cout<<z;
}
cout<<endl;
}
return 0;
But the Output is this
12
12
1234
1234
123456
123456
12345678
12345678
12345678910
12345678910
123456789101112
123456789101112
1234567891011121314
1234567891011121314
12345678910111213141516
12345678910111213141516
123456789101112131415161718
123456789101112131415161718
1234567891011121314151617181920
1234567891011121314151617181920
** Process exited - Return Code: 0 **
Expected Output is this
12
1234
123456
12345678
12345678910
123456789101112
1234567891011121314
12345678910111213141516
123456789101112131415161618
1234567891011121314151616181920
| For example you can change the inner for loop the following way
for(int y=1;y<=20;y++)
{
for( int z=1; z <= 2 * y; z++)
{
cout << z;
}
cout << endl;
}
If you want to output only 10 lines then change the condition in the outer loop
for(int y=1;y<=10;y++)
{
for( int z=1; z <= 2 * y; z++)
{
cout << z;
}
cout << endl;
}
|
70,340,507 | 70,340,744 | How to pass a vector or a valarray as an argument to a C++ template function | I feel this is probably an elementary question, but I can't find a simple answer after quite a bit of searching, so I thought I'd ask.
I have a function that is meant to return the nth percentile value in a container, but for legacy reasons the array can be either a vector or valarray, and it can contain doubles or floats. What is the correct syntax for the function?
At the moment I have:
template <template <class> class vType, class elType>
elType GetPercentile(vType<elType>& vData, double dPercentile)
{
int iOffset = int(dPercentile * vData.size());
std::nth_element(begin(vData), begin(vData) + iOffset, end(vData));
return static_cast<elType>(vData[iOffset]);
}
This compiles OK when passing a valarray, but fails for a vector:
'elType GetPercentile(vType &,double)': could not deduce template argument for 'vType &' from 'std::vector<float,std::allocator>'
Is there a way of doing this? It seems silly to duplicate the code for the two container types. (And if there are any comments on the code itself, that would be fine too.)
Many thanks for any advice.
Bill H
| std::vector has 2 template parameters. The second one is the allocator, which has a default value so you normally don't use it.
However, prior to c++17 template template parameters would only match if the number of template arguments where the same. In c++17 this was relaxed a bit and it's since allowed to match a template with more template parameters as long as the remaining ones have default arguments.
Regardless of this, I would propose a solution that uses the member type in both containers, value_type.
#include <vector>
#include <algorithm>
#include <valarray>
template <class T>
auto GetPercentile(T& vData, double dPercentile)
{
using elType = typename T::value_type;
int iOffset = int(dPercentile * vData.size());
std::nth_element(begin(vData), begin(vData) + iOffset, end(vData));
return static_cast<elType>(vData[iOffset]);
}
int main() {
auto v = std::vector<int>{1,2,3,4,5};
GetPercentile(v, 2);
auto a = std::valarray<int>(5, 5);
GetPercentile(a, 2);
}
|
70,340,668 | 70,344,142 | Which GL blend mode for blending the same color in source and destination, and getting the same color back? | I have an texture that is with a solid background (let's say navy blue, #000080) and white text on it. Even though the texture is a single file with both background and text, I'd like to cause just the text to fade out.
I've prepared a second texture, just solid navy blue without any text. I'd like to "fade" the text out by modifying the texture's alpha layer, until just the second texture (blue with no text) remains.
My problem is that when I start making the front layer (color + text) transparent, the text fades out as I expect, but the resulting blue is darker. The blue I see is the background color blue (#000080), tinted dark by the semitransparent layer in front of it. After some reading, it looks like I want to modify OpenGL's blend mode for this part.
I'm looking for a blend mode that generates:
#000080 + #000080*tranparency = #000080
#000080 + #FFFFFF*transparency = #FFFFFF*transparency
I've tried GL_MIN and GL_MAX, but those don't seem to be the ones I'm looking for here...
| You shouldn't need anything more than just:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBlendEquation(GL_ADD);
glEnable(GL_BLEND);
Which corresponds to the following:
original_pixel = [0, 0, 0.5, 1]
incoming_pixel = [0, 0, 0.5, 0.5]
final_pixel = incoming_pixel * 0.5 + original_pixel * (1 - 0.5);
Which should leave the colour intact.
You shouldn't need the second texture - just draw an untextured quad with the correct colour.
|
70,340,719 | 70,340,785 | Why does the first element outside of a defined array default to zero? | I'm studying for the final exam for my introduction to C++ class. Our professor gave us this problem for practice:
Explain why the code produces the following output: 120 200 16 0
using namespace std;
int main()
{
int x[] = {120, 200, 16};
for (int i = 0; i < 4; i++)
cout << x[i] << " ";
}
The sample answer for the problem was:
The cout statement is simply cycling through the array elements whose subscript is being defined by the increment of the for loop. The element size is not defined by the array initialization. The for loop defines the size of the array, which happens to exceed the number of initialized elements, thereby defaulting to zero for the last element. The first for loop prints element 0 (120), the second prints element 1 (200), the third loop prints element 2 (16) and the forth loop prints the default array value of zero since nothing is initialized for element 3. At this point i now exceeds the condition and the for loop is terminated.
I'm a bit confused as to why that last element outside of the array always "defaults" to zero. Just to experiment, I pasted the code from the problem into my IDE, but changed the for loop to for (int i = 0; i < 8; i++). The output then changed to 120 200 16 0 4196320 0 547306487 32655. Why is there not an error when trying to access elements from an array that is outside of the defined size? Does the program just output whatever "leftover" data was there from the last time a value was saved to that memory address?
|
I'm a bit confused as to why that last element outside of the array
always "defaults" to zero.
In this declaration
int x[] = {120, 200, 16};
the array x has exactly three elements. So accessing memory outside the bounds of the array invokes undefined behavior.
That is, this loop
for (int i = 0; i < 4; i++)
cout << x[i] << " ";
invokes undefined behavior. The memory after the last element of the array can contain anything.
On the other hand, if the array were declared as
int x[4] = {120, 200, 16};
that is, with four elements, then the last element of the array that does not have an explicit initializer will be indeed initialized to zero.
|
70,340,826 | 70,341,204 | Is there a way to get the function type of a pointer to a member function? | If you have a pointer to a member function like so:
struct Foo { void func() {} };
void(Foo::*funcPtr)() = &Foo::func;
Is there a way to get the type of the function, with the Foo:: removed?
I.e.,
void(Foo::*)() -> void(*)()
int(Foo::*)(int, double, float) -> int(*)(int, double, float)
You get the idea.
The goal is to make std::function accept a functor like this:
struct Functor { void operator()(...){} }
Functor f;
std::function< magic_get_function_type< decltype(Functor::operator()) >::type > stdfunc{f};
Is it possible?
| To answer your question, it is possible with a simple template:
template <typename Return, typename Class, typename... Args>
Return(*GetSig(Return(Class::*)(Args...)))(Args...);
This defines a function called GetSig that takes as parameter a member function pointer and essentially extracts the Return type and the Args... and returns it as a non-member function pointer.
Example usage:
class C;
int main() {
using FuncType = int(C::*)(double, float);
FuncType member_pointer;
decltype(GetSigType(member_pointer)) new_pointer;
// new_pointer is now of type int(*)(double, float) instead of
// int(C::*)(double, float)
}
|
70,340,966 | 70,341,376 | Constructor overloading with variadic arguments | First, my code:
#include <iostream>
#include <functional>
#include <string>
#include <thread>
#include <chrono>
using std::string;
using namespace std::chrono_literals;
class MyClass {
public:
MyClass() {}
// More specific constructor.
template< class Function, class... Args >
explicit MyClass( const std::string & theName, Function&& f, Args&&... args )
: name(theName)
{
runner(f, args...);
}
// Less specific constructor
template< class Function, class... Args >
explicit MyClass( Function&& f, Args&&... args ) {
runner(f, args...);
}
void noArgs() { std::cout << "noArgs()...\n"; }
void withArgs(std::string &) { std::cout << "withArgs()...\n"; }
template< class Function, class... Args >
void runner( Function&& f, Args&&... args ) {
auto myFunct = std::bind(f, args...);
std::thread myThread(myFunct);
myThread.detach();
}
std::string name;
};
int main(int, char **) {
MyClass foo;
foo.runner (&MyClass::noArgs, &foo);
foo.runner (&MyClass::withArgs, &foo, std::string{"This is a test"} );
MyClass hasArgs(string{"hasArgs"}, &MyClass::withArgs, foo, std::string{"This is a test"} );
std::this_thread::sleep_for(200ms);
}
I'm trying to build a wrapper around std::thread for (insert lengthy list of reasons). Consider MyClass here to be named ThreadWrapper in my actual library.
I want to be able to construct a MyClass as a direct replacement for std::thread. This means being able to do this:
MyClass hasArgs(&MyClass::withArgs, foo, std::string{"This is a test"} );
But I also want to optionally give threads a name, something like this:
MyClass hasArgs(string{"hasArgs"}, &MyClass::withArgs, foo, std::string{"This is a test"} );
So I created two template constructors. If I only want to do one or the other and only use a single template constructor, what I'm doing is fine.
With the code as written, if you compile (g++), you get nasty errors. If I comment out the more specific constructor, I get a different set of nasty errors. If I comment out the less specific constructor (the one that doesn't have a const std::string & arg), then everything I'm trying to do works. That is, the one with std::string is the right one, and it works.
What's happening is that if I have both constructors, the compiler picks the less specific one each time. I want to force it to use the more specific one. I think I can do this in C++ 17 with traits, but I've never used them, and I wouldn't know where to begin.
For now, I'm going to just use the more specific version (the one that takes a name) and move on. But I'd like to put the less specific one back in and use it when I don't care about the thread names.
But is there some way I can have both templates and have the compiler figure out which one based on whether the first argument is either a std::string or can be turned into one?
No one should spend significant time on this, but if you look at this and say, "Oh, Joe just has to..." then I'd love help. Otherwise I'll just live with this not being 100% a direct drop-in replacement, and that's fine.
| I would make the constructors viable iff function is invocable with the arguments:
C++20 concepts
class MyClass {
public:
MyClass() {}
// More specific constructor.
template< class Function, class... Args >
requires std::invocable<Function, Args...>
explicit MyClass( const std::string & theName, Function&& f, Args&&... args )
: name(theName)
{
runner(f, args...);
}
// Less specific constructor
template< class Function, class... Args >
requires std::invocable<Function, Args...>
explicit MyClass( Function&& f, Args&&... args ) {
runner(f, args...);
}
};
C++17
class MyClass {
public:
MyClass() {}
// More specific constructor.
template< class Function, class... Args,
std::enable_if_t<std::is_invocable_v<Function, Args...>, std::nullptr_t> = nullptr>
explicit MyClass( const std::string & theName, Function&& f, Args&&... args )
: name(theName)
{
runner(f, args...);
}
// Less specific constructor
template< class Function, class... Args,
std::enable_if_t<std::is_invocable_v<Function, Args...>, std::nullptr_t> = nullptr>
explicit MyClass( Function&& f, Args&&... args ) {
runner(f, args...);
}
};
However
Now if you put in this code in your example it won't compile because there is another problem in your code:
You pass an rvalue string but your withArgs take an lvalue reference so the concept it not satisfied. Your code works without the concept because you don't forward the arguments to runner so runner doesn't receive an rvalue reference. This is something you need to fix. Forward the arguments to runner and then to bind and withArgs to take by const &.
|
70,341,186 | 70,341,432 | I am using modulo operator, but it still giving me a negative number | I am trying to solve a programming problem in c++ (version : (MinGW.org GCC Build-2) 9.2.0)
I am using modulo operator to give answer in int range but for 6 ,it is giving me -ve answerwhy is this happening??
my code :
#include <cmath>
#include <iostream>
using namespace std;
int balancedBTs(int h) {
if (h <= 1) return 1;
int x = balancedBTs(h - 1);
int y = balancedBTs(h - 2);
int mod = (int)(pow(10, 9) + 7);
int temp1 = (int)(((long)(x) * x) % mod);
int temp2 = (int)((2 * (long)(x) * y) % mod);
int ans = (temp1 + temp2) % mod;
return ans;
}
int main()
{
int h;
cin >> h;
cout << balancedBTs(h) << endl;
return 0;
}
output :
| The code makes two implicit assumptions:
int is at least 32 bit (otherwise the 1,000,000,007 for mod will not fit)
long is bigger than int (to avoid overflows in the multiplication)
Neither of these assumptions are guarantee by the standard https://en.cppreference.com/w/cpp/language/types
I don't have access to the same platform in the question, but I can reproduce the output exactly if I remove the cast to long in the assignment of temp1 and temp2 (effectively simulating a platform were sizeof int and long is both 4).
You can verify if the second assumptions hold in your platform checking the sizeof(int) and sizeof(long).
|
70,341,367 | 70,341,534 | Using a C++ std::vector as a queue in a thread | I would like to have items added to a queue in one thread via in an asynchronous web request handler:
void handleRequest(item) {
toProcess.push_back(item);
}
There is a background thread that constantly processes these queue items as follows:
while(true) {
for(auto item : toProcess) { doSomething(item); }
toProcess.clear();
}
Clearly this isn't thread safe ... you might add an item to toProcess right when the for loop finishes and thus have it cleared out without being processed. What would be the best model to program something like this?
| I'm going to use std::atomic<T>::wait which is a C++20 feature, there is a way to do it with condition variables too however, and they exist since C++11.
Include <atomic> and <mutex>
You will need a member atomic_bool.
std::atomic_bool RequestPassed = false;
and a member mutex
std::mutex RequestHandleMutex;
Your handleRequest function would then become
void handleRequest(item) {
std::lock_guard<std::mutex> lg(RequestHandleMutex)
toProcess.push_back(item);
RequestPassed.store(true);
RequestPassed.notify_all();
}
and your loop would be this
while(true) {
RequestPassed.wait(false);
std::lock_guard<std::mutex> lg(RequestHandleMutex)
/* handle latest item passed */
RequestPassed.store(false);
}
This way, the while thread waits instead of constantly iterating (saving cpu power and battery). If you then use handleRequest, the atomic_bool gets notified to stop waiting, the request is handled (mutex is locked so no new requests can come while this happens), RequestPassed is reset to false, and the thread waits for the next request.
|
70,341,467 | 70,341,583 | How is 'if (x)' where 'x' is an instance of a class, not an implicit conversion? | According to cppreference.com an explicit conversion function cannot be used for implicit conversions. As an example they have this:
struct B
{
explicit B(int) { }
explicit B(int, int) { }
explicit operator bool() const { return true; }
};
int main()
{
...
if (b2) ; // OK: B::operator bool()
...
}
I would have thought that 'if (b2)' was an implicit conversion and therefore not able to use the explicit conversion function. So what would be an example of an implicit conversion that wouldn't be allowed?
| Contextual conversions
In the following contexts, the type bool is expected and the
implicit conversion is performed if the declaration bool t(e); is
well-formed (that is, an explicit conversion function such as explicit
T::operator bool() const; is considered). Such expression e is said to
be contextually converted to bool.
the controlling expression of if, while, for;
...
|
70,341,661 | 70,341,944 | C++/Qt: How to create a busyloop which you can put on pause? | Is there a better answer to this question than creating a spinlock-like structure with a global boolean flag which is checked in the loop?
bool isRunning = true;
void busyLoop()
{
for (;;) {
if (!isRunning)
continue;
// ...
}
}
int main()
{
// ...
QPushButton *startBusyLoopBtn = new QPushButton("start busy loop");
QObject::connect(startBusyLoopBtn, QPushButton::clicked, [](){ busyLoop(); });
QPushButton *startPauseBtn = new QPushButton("start/pause");
QObject::connect(startPauseBtn, QPushButton::clicked, [](){ isRunning = !isRunning; });
// ...
}
To begin with, we waste the CPU time while checking the flag. Secondly, we need two separate buttons for this scheme to work. How can we use Qt's slot-signal mechanism for a simpler solution?
| You can use std::condition_variable:
std::mutex mtx;
std::condition_variable cv_start_stop;
std::thread thr([&](){
/**
* this thread will notify and unpause the main loop 3 seconds later
*/
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
cv_start_stop.notify_all();
});
bool paused = true;
while (true)
{
if (paused)
{
std::unique_lock<std::mutex> lock(mtx);
cv_start_stop.wait(lock); // this will lock the thread until notified.
std::cout << "thread unpaused\n";
paused = false;
}
std::cout << "loop goes on until paused\n";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
This will not brutally check for a flag to continue, instead, it will put thread to sleep until notified.
You will simply make paused = true; to pause and cv_start_stop.notify_one(); or cv_start_stop.notify_all(); to unpause.
|
70,341,803 | 70,342,206 | Is this ? ternary operation legal? | I'm no expert, but I do like to learn and understand. With that in mind I wrote the following in the Arduino IDE:
lockout[idx] ? bulb[idx].off() : bulb[idx].on();
to replace this:
if (lockout[idx]) bulb[idx].off(); else bulb[idx].on();
lockout[] is an array of bool, and bulb[] is an array of a class, with .off and .on methods.
I've looked around for examples and never seen this usage of the ? ternary operator. And what I've read seems to say that this should not work.
But it does compile. So is this in fact legitimate C++?
| Yes, this is legitimate C++. While that operator is commonly called the ternary operator, it is called the conditional operator in the C++ standard, and it is defined in the section named "expr.cond".
The C++ standard explicity says it is OK for both the second and third operands to have type void. So the standard writers knew that people might want to use this operator as a short way to write if statements, like you are doing.
If the types of the second or third operands are not void, then the standard says "an attempt is made to convert each of those operands to the type of the other" and it goes into detail about what that means.
For reference, the version of the C++ standard I am referring to is N4296, so it's a little old but I don't think that matters.
|
70,342,314 | 70,342,518 | cin input user for dynamic allocation of array of strings | i'm new at this, learn c++, try to dynamic allocate a array of strings and input every string by the user. so at first, the user input the number of strings, and then put every string using cin>>
int main() {
int numberOfTeams;
char** Teams;
cout << "Enter the number of teams " << endl;
cin >> numberOfTeams;
Teams = new char* [numberOfTeams] ;
for (int i = 0; i < numberOfTeams; i++) {
cin >> Teams[i];
}
delete[] Teams;
return 0;
}
the program throw me out after cin one string.
the error i get is :
Exception thrown: write access violation.
**_Str** was 0xCEDECEDF.
i cant use "string" veriable, only array of chars.
thank you all
| Something like this
const int MAX_STRING_SIZE = 1024;
int main() {
int numberOfTeams;
char** Teams;
std::cout << "Enter the number of teams " << std::endl;
std::cin >> numberOfTeams;
Teams = new char*[numberOfTeams];
for (int i = 0; i < numberOfTeams; i++) {
Teams[i] = new char[MAX_STRING_SIZE];
std::cin >> Teams[i];
}
for(int i = 0; i < numberOfTeams; ++i) {
delete [] Teams[i];
}
delete [] Teams;
return 0;
}
|
70,342,456 | 70,342,572 | Speeds of 3D Vector Versus 3D Array of Varying Size | I'm designing a dynamic hurtbox for characters in a text-based game, which catches the locations of hits (or misses) of a weapon swung at them. The location (indices) and damage (magnitude) of hits are then translated into decreases in corresponding limb health variables for a character. My thoughts are that this hurtbox would best be implemented using a class with some 3D vector/array member.
Naturally, I might want varying dimensions of the 3D container for different sizes of enemy, but I'm aware that size is usually determined upon initialization. So here's my question:
Would it be more efficient to use a C-style dynamic array, the size of which I can decide and allocate inside a parameterized constructor, like so?
class hurtBox {
private:
int ***hurtBoxMatrix;
public:
hurtBox(int l, int w, int h) {
hurtBoxMatrix = new int**[l];
for (int i = 0; i < l; i++) {
hurtBoxMatrix[i] = new int*[w];
for (int j = 0; j < w; j++) {
hurtBoxMatrix[i][j] = new int[h] ();
}
}
}
};
Or, would a vector that I push elements into, up to my desired dimensions, suffice?
class hurtBox {
private:
vector<vector<vector<int>>> hurtBoxMatrix;
public:
hurtBox(int l, int w, int h) {
for (int i = 0; i < l; i++) {
hurtBoxMatrix.push_back(vector<vector<int>>);
for (int j = 0; j < w; j++) {
hurtBoxMatrix[i].push_back(vector<int>);
for (int k = 0; k < h; k++) {
hurtBoxMatrix[i][j].push_back(0);
}
}
}
}
};
I imagine the former, since that first allocation is constant time, right? Is there a way to do this that's better than either of these?
Thanks in advance.
| You'd be better off simply allocating the 3D array in a single allocation, and use indexing to access the elements. Allocation for the std::vector storage can then be handled in the constructor for std::vector.
In general it's best to avoid:
multiple allocations
repeatedly calling push_back
class hurtBox {
private:
vector<int> hurtBoxMatrix;
int m_l;
int m_w;
int m_h;
public:
hurtBox(int l, int w, int h)
: hurtBoxMatrix(l * w * h), m_l(l), m_w(w), m_h(h) {}
int& operator (int i, int j, int k) {
return hurtBoxMatrix[ I*m_w*m_h + j*m_w + k ];
}
const int operator (int i, int j, int k) const {
return hurtBoxMatrix[ i*m_w*m_h + j*m_w + k ];
}
};
|
70,342,590 | 70,342,960 | Equivalent of python list multiplying with a scale in c++ | How would you code list multiplying with a scale in c++?
In python I would do:
lst = [1,2,3]
lst*3 # we will get [1,2,3,1,2,3,1,2,3]
What is the c++ equivalent of that?
| If you really need the operation of multiplication, for example, you are developing some math library, you can consider the operator overloading. Otherwise, I suggest you throwing the python style away while working with C++, just use std::copy or vector::insert with a loop to insert repeated elements into a vector.
std::vector<int>& operator*(std::vector<int>& vec, std::size_t n) {
auto initSize = vec.size();
for (std::size_t i = 0; i < n - 1; ++i) {
vec.insert(vec.end(), vec.begin() + initSize * i, vec.end());
}
return vec;
}
// commutative principle for multiplication
std::vector<int>& operator*(std::size_t n, std::vector<int>& vec) {
return operator*(vec, n);
}
int main()
{
std::vector<int> vec {1, 2, 3};
vec = vec * 3; // 3 * vec is OK too
for (auto val : vec) {
std::cout << val << ' ';
}
return 0;
}
|
70,342,675 | 70,342,777 | What is the best way to determine an intersection between 2D shapes on a cartesian grid? | The function below is supposed to determine whether two objects of the movingBall struct are "touching" with each other
bool areBallstouching(movingBall one, movingBall two)
{
int xMin, xMax, yMin, yMax;
int TxMin, TxMax, TyMin, TyMax;
xMin = one.xPosition - one.radius;
xMax = one.xPosition + one.radius;
yMin = one.yPosition - one.radius;
yMax = one.yPosition + one.radius;
//===================================
TxMin = two.xPosition - two.radius;
TxMax = two.xPosition + two.radius;
TyMin = two.yPosition - two.radius;
TyMax = two.yPosition + two.radius;
//=======================================
vector <int> xrange, yrange, Txrange, Tyrange;
bool xtouch = false; bool ytouch = false;
for (int i = xMin; i < xMax; i++)
{
xrange.push_back(i);
}
for (int i = yMin; i < yMax; i++)
{
yrange.push_back(i);
}
for (int i = TxMin; i < TxMax; i++)
{
Txrange.push_back(i);
}
for (int i = TyMin; i < TyMax; i++)
{
Tyrange.push_back(i);
}
for (int i = 0; i < xrange.size(); i++)
for (int j = 0; j < Txrange.size(); j++)
if (xrange[i] == Txrange[j])
xtouch = true;
for (int i = 0; i < yrange.size()-1; i++)
for (int j = 0; j < Tyrange.size()-1; j++)
if (yrange[i] == Tyrange[j])
ytouch = true;
if (xtouch == true && ytouch == true)
{
return true;
}
else
{
return false;
}
}
I reasoned that the balls can only be touching each other if they share any two coordinates. If they share only an x-coordinate, they will be aligned vertically but the bottom point of the topmost ball will not contact the top point of the bottom-most ball. If they share only a y-coordinate, they will be aligned horizontally but the right-most point of the left-most ball will not touch the left-most point of the right-most ball.
The attached picture demonstrates this reasoning. When I implemented the code, I did not achieve the results I wanted. The program was not able to properly detect the intersections between the two circles.
| Mathematically, the point where two circles touch will separate their center positions by a distance equal to the sum of the two radii. It follows:
if distance between centers is less than the sum of radii, circles intersect;
if distance between centers is greater than the sum of radii, circles do not intersect (or touch).
So, all you need is a simple distance calculation with basic Pythagoras.
float dx = two.xPosition - one.xPosition;
float dy = two.yPosition - one.yPosition;
float distsq = dx * dx + dy * dy; // square distance between centers
float r = one.radius + two.radius; // sum of radii
float rsq = r * r;
bool intersect_or_touch = (distsq <= rsq);
Note that above we can operate in the domain of square distance and square radii to avoid needing to use a sqrt calculation.
|
70,342,964 | 70,343,007 | c++ header file not found when compiling ios project in xcode | When I built an iOS project, I got an error "'tuple' file not found". Seems xcode is not trying to look for c++ header files.
The error message is:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS15.0.sdk/usr/include/simd/vector_make.h:5310:10: 'tuple' file not found
In vector_make.h, tuple is included:
#include <tuple>
This is originated from AVFoundation.h included by a c++ file "tdav_apple.mm":
#if TDAV_UNDER_APPLE
#if TDAV_UNDER_IPHONE || TDAV_UNDER_IPHONE_SIMULATOR
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#endif
How can I fix it? Thanks for your help!
| I'd check and make sure your language version is at least C++11, since that's when tuple was introduced.
Failing that I'd verify the .mm file is properly tagged as C++ in the project file (select the file, then open the right hand side "File inspector" thing.)
|
70,343,285 | 70,343,437 | Check what files a program reads from a computer (C++) | I have a program that reads files (given to it by the user) from the computer and performs operations on these files. However, the program isn't working. I input a valid file with a valid path and the program says it is reading this valid file, however, it doesn't find the files. I have verified that the method I use to read the files works.
So, this prompts my question. Is it possible for a C++ program to track what files are being read by a specific program, and tell me the path it is trying to read?
| For Linux, the strace utility is the answer (as mentioned by Peter in a comment). You probably have it installed already, so just run strace your_program_name and you can see all the system calls the program is running, and their arguments and return codes. You should focus on the open calls.
|
70,343,367 | 70,345,525 | Splitting string with colons and spaces? | So I've made my code work for separating the string:
String c;
for (int j = 0 ; j < count; j++) {
c += ip(ex[j]);
}
return c;
}
void setup() {
Serial.begin(9600);
}
I have had no luck with this, so any help would be greatly appreciated!
| I would simply add a delimiter to your tokenizer. From a strtok() description the second parameter "is the C string containing the delimiters. These may vary from one call to another".
So add a 'space' delimiter to your tokenization: ex[i] = strtok(NULL, ": "); trim any whitespace from your tokens, and throw away any empty tokens. The last two shouldn't be necessary, because the delimiters won't be part of your collected tokens.
|
70,343,841 | 70,343,886 | Can function templates be instantiated based on the result of runtime if else conditions without creating class templates in C++? | If following is the definition of simple function template:
template<typename T>
T compare(T a, T b)
{
return a>b ? a : b;
}
Can it be called with different template parameter based on some user input during runtime, WITHOUT creating class templates, with different T values as follows for example:
char type;
cout<<"Enter type: ";
cin>>type;
if( type=='i')
{
int x=compare<int>(3,6);
}
else if( type=='d' )
{
double z=compare<double>(5.1,7.9);
}
..so on
| No. If you want to determine the type at runtime then you need to do what are you doing (the if else)
There are more advanced techniques for more advance uses, like using polymorphism with a table of callables, but in essence they do the same thing, just in a fancier way.
|
70,343,892 | 70,344,041 | C++ sockets: accept() hangs when client calls connect(), but accept() responds to HTTP GET request | I'm trying to write a demo server/client program in C++. I first ran my server program on my Macbook, with ngrok on and forwarding a public address on the Internet to a local address on my machine. I'm seeing something that I don't understand when I try to run my client program to connect to the server:
If the client tries to connect to localhost at the local port defined in the server program, the server accepts as expected and the client successfully connects,
If the client tries to connect to the ngrok server address at port 80 (default for ngrok), then the client connects, but the server is still blocked at the accept call. (This I don't understand!)
If I send an HTTP GET request to the ngrok server address, the server successfully accepts the connection.
Why do I see these? In the ideal case, I want my server to accept connections from my client program, not just respond to the HTTP GET request.
Here's my code if that helps: For the client,
#include "helpers.hh"
#include <cstdio>
#include <netdb.h>
// usage: -h [host] -p [port]
int main(int argc, char** argv) {
const char* host = "x.xx.xx.xx"; // use the server's ip here.
const char* port = "80";
// parse arguments
int opt;
while ((opt = getopt(argc, argv, "h:p:")) >= 0) {
if (opt == 'h') {
host = optarg;
} else if (opt == 'p') {
port = optarg;
}
}
// look up host and port
struct addrinfo hints, *ais;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // use TCP
hints.ai_flags = AI_NUMERICSERV;
if (strcmp(host, "ngrok") == 0) {
host = "xxxx-xxxx-xxxx-1011-2006-00-27b9.ngrok.io";
}
int r = getaddrinfo(host, port, &hints, &ais);
if (r != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(r));
exit(1);
}
// connect to server
int fd = -1;
for (auto ai = ais; ai && fd < 0; ai = ai->ai_next) {
fd = socket(ai->ai_family, ai->ai_socktype, 0);
if (fd < 0) {
perror("socket");
exit(1);
}
r = connect(fd, ai->ai_addr, ai->ai_addrlen);
if (r < 0) {
close(fd);
fd = -1;
}
}
if (fd < 0) {
perror("connect");
exit(1);
}
freeaddrinfo(ais);
//
printf("Connection established at fd %d\n", fd);
FILE* f = fdopen(fd, "a+");
fwrite("!", 1, 1, f);
fclose(f);
while (true) {
}
}
And for the server:
#include "helpers.hh"
void handle_connection(int cfd, std::string remote) {
(void) remote;
printf("Received incoming connection at cfd: %d\n", cfd);
usleep(1000000);
printf("Exiting\n");
}
int main(int argc, char** argv) {
int port = 6162;
if (argc >= 2) {
port = strtol(argv[1], nullptr, 0);
assert(port > 0 && port <= 65535);
}
// Prepare listening socket
int fd = open_listen_socket(port);
assert(fd >= 0);
fprintf(stderr, "Listening on port %d...\n", port);
while (true) {
struct sockaddr addr;
socklen_t addrlen = sizeof(addr);
// Accept connection on listening socket
int cfd = accept(fd, &addr, &addrlen);
if (cfd < 0) {
perror("accept");
exit(1);
}
// Handle connection
handle_connection(cfd, unparse_sockaddr(&addr, addrlen));
}
}
| Contrary to the typical port forwarding done in the local router, ngrok is not a port forwarder at the transport level (TCP) but it is a request forwarder at the HTTP level.
Thus if the client does a TCP connect to the external ngrok server nothing will be forwarded yet. Only after the client has send the HTTP request the destination will be determined and then this request will be send to the ngrok connector on the internal machine, which then will initiate the connection to the internal server and forward the request.
|
70,344,624 | 70,344,717 | source is compiled without proper #include | I have a very simple c++ source like this:
#include <iostream>
int main() {
srand(time(NULL));
}
I am using g++ to compile like this :
g++ ./test.cpp
but it successfully compiles despite the fact that time() function is defined in ctime and it is not included with #include
my professor at university runs the code with visual studio (vc++) but he is unable to run the code without including ctime
Am I missing something here ?
by the way my g++ version is :
g++ (Ubuntu 11.2.0-7ubuntu2) 11.2.0
| First of all, on my platform, it didn't compile successfully when I removed #include <iostream>
I am using WSL2 ubuntu 20.04, compiler i used g++ and clang++.
Whichever compiler it is, it gives the error:
>>> g++ t.cpp
t.cpp: In function ‘int main()’:
t.cpp:2:16: error: ‘NULL’ was not declared in this scope
2 | srand(time(NULL));
| ^~~~
t.cpp:1:1: note: ‘NULL’ is defined in header ‘<cstddef>’; did you forget to ‘#include <cstddef>’?
+++ |+#include <cstddef>
1 | int main() {
t.cpp:2:11: error: ‘time’ was not declared in this scope
2 | srand(time(NULL));
| ^~~~
t.cpp:2:5: error: ‘srand’ was not declared in this scope
2 | srand(time(NULL));
| ^~~~~
>>>clang t.cpp
t.cpp:2:16: error: use of undeclared identifier 'NULL'
srand(time(NULL));
^
1 error generated.
I think you can use the compile option -E to prompt the compiler to do only preprocessing and to see the preprocessed file.
like this:
g++ t.cpp -E -o pre_proccessed.cpp
Determine whether the compiler did what you suspect it did during the compilation process, "automatically include the file"
But, when I add #include <iostream>
It did success.
So, I did this:
>>>g++ t.cpp -E -o t_.cpp
>>>cat t_.cpp | grep srand
extern void srandom (unsigned int __seed) throw ();
extern int srandom_r (unsigned int __seed, struct random_data *__buf)
extern void srand (unsigned int __seed) throw ();
extern void srand48 (long int __seedval) throw ();
extern int srand48_r (long int __seedval, struct drand48_data *__buffer)
using ::srand;
This explains why its compilation succeeded, because the iostream file included in this platform has the definition of this function in it.
In addition, look at this problam
In fact, stl are allowed to include each other.
But even though it is defined in this header file, you cannot rely on it, some versions of the iostream implementation do not include this.
What you should do is to actively include the cstdlib file when using srand, don't worry about the multiple inclusion problem, std,stl itself can handle multiple inclusion very well, and modern compilers can also handle this problem very well.
|
70,345,733 | 70,362,457 | Installing wxPython on Windows: DistutilsPlatformError: Microsoft Visual C++ 14.2 or greater is required | I have installed:
Python 3.10.1
PyCharm Community 2021.3
Visual Studio Build Tools 2022, including:
C++ Build Tools Core Features
C++ 2022 Redistributable Update
C++ core desktop features
MSVC v143 - VS 2022 C++ x64/x86 build tools (Latest)
Windows 10 SDK (10.0.19041.0)
C++ CMake tools for Windows
Testing tools core features - Build Tools
C++ AddressSanitizer
C++/CLI support for v143 build tools (Latest)
C++ Modules for v143 build tools (x64/x86 - experimental)
When trying to install wxPython in my project's virtualenv, I get this error:
distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.2 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
Both the error and anything I can find on the internet (including here) tells me to download C++ build tools and install C++ 14.2 or greater / the latest version. I have:
done that (see the list above),
rebooted
venv/Scripts/pip install --upgrade setuptools
venv/Scripts/pip install --upgrade wheel
venv/Scripts/pip install --upgrade pip
What am I missing here? Is there some sort of path variable that I need to configure somewhere so pip/wheel/setuptools knows where to find the compiler?
| I have the same problem. Solved for me to use Python 3.9.9.
Its maybe about a distutils problem in Python 3.10.1 with this warning from msvc9compiler.py:
DeprecationWarning: The distutils package is deprecated and slated for
removal in Python 3.12
This leads to:
raise DistutilsPlatformError("Unable to find vcvarsall.bat")
|
70,346,700 | 70,346,792 | deque.at No Maching Function | I am trying to deque (a string element) from a deque data structure. But I am getting and error:
error: no matching function for call to ‘std::__cxx11::basic_string::basic_string(__gnu_cxx::__alloc_traitsstd::allocator<std::array<std::__cxx11::basic_string<char, 1> >, std::arraystd::__cxx11::basic_string<char, 1> >::value_type&)’
26 | string record = (string)records.at(0);
deque<array<string, 1>> records;
string data("hello this is 1st record");
array<string, 1> buffer{data};
records.push_back(buffer);
string record = (string)records.at(0); //error is reported at this line
printf("%s\n", record.c_str());
Can someone please give me a hint what I am doing wrongly.
As background, I have to cache the last 100 text messages, so I am using deque for this purpose.
| It is not quite clear why you are using array as elements. The value returned from at is not a string but an array.
deque<array<string, 1>> records;
string data("hello this is 1st record");
array<string, 1> buffer{data};
records.push_back(buffer);
string record = records.at(0)[0];
^^ get first element in deque
^^ get first element in array
Do not use c-style casts ((string)...). They are almost always wrong (and when they are not, they should be replaced with a safer C++ cast). If you do not use the array (why? when it only holds a single element?) the code is
deque<string> records;
string data("hello this is 1st record");
records.push_back(data);
string record = records.at(0);
^^ get first element in deque
|
70,347,206 | 70,347,603 | Class with no blocking methodes with multithreading | I am programming a class which should use multithreading features.
The goal is that I don't have any blocking methods from the outside although I use libraries in the class that have blocking functions.
I want to run them in their own threads.
Unfortunately I get a memory fault (core dumped) error.
What would be the best practice in c++11 to implement something like this and why do I get the error,how can I specify the memory for the function I want to call in the thread best in advance?
My Class
..
class foo {
void startUp();
foo();
~foo();
std::thread foo_worker;
int retValue;
};
void foo::startUp() {
int retValue = 0;
std::thread t([this] () {
retValue = blocking_lib_func();
});
foo_worker = std::move(t);
}
foo::~foo() {
....
foo_worker.join();
}
My Main
int main()
foo test();
test.statUp()
}
| The lambda associated with your thread is capturing a reference to local stack variable. When startUp returns, the thread will continue on, but the address of retValue is now off limits, including to the thread. The thread will create undefined behavior by trying to assign something to that reference to retValue. That is very likely the source of the crash that you describe. Or worse, stack corruption on the main thread corrupting your program in other ways.
The solution is simple. First, make retValue a member variable of your class. And while we are at it, no reason for foo_worker to be a pointer.
class foo {
public:
void startUp();
foo();
~foo();
private:
std::thread foo_worker;
int retValue;
};
Then your startUp code can be this. We can use std::move to move the thread from the local t thread variable to the member variable of the class instance.
void foo::startUp() {
std::thread t([this] () {
retValue = blocking_lib_func(); // assign to the member variable of foo
});
foo_worker = std::move(t);
}
Then your destructor can invoke join as follows:
foo::~foo() {
....
foo_worker.join();
}
And as other in the comments have pointed out, volatile isn't useful. It's mostly deprecated as a keyword when proper thread and locking semantics are used.
|
70,347,311 | 70,348,831 | How is the string layout of cpp? | I wondered how char sequence(string) arranged in RAM, so make below testing with c++.
The compiler environment is 64bit system, cygwin on windows10.
#include <iostream>
using namespace std;
int main() {
char* c1 = "01";
cout << "string to print:" << endl;
cout << c1 << endl;
cout << "the address in stack of the pointer:" << endl;
cout << &c1 << endl;
cout << "the address in heap for the first letter in the string:" << endl;
cout << (void*)c1 << endl;
cout << "the address in heap for the second letter in the string:" << endl;
cout << (void*)(++c1) << endl;
}
output is:
string to print:
01
the address in stack of the pointer:
0xffffcc28
the address in heap for the first letter in the string:
0x100403001
the address in heap for the second letter in the string:
0x100403002
I recognize that the address of char '0' and '1' just offset 1byte.
So is that mean the two chars just arrange one by one in one ram unit?
As below illustration?
/*
* 64bit ram
* |-------------------------64bits--------------------------------|
* stack | |
*
* heap | 8bits | 8bits | 8bits | 8bits | 8bits | 8bits | '1' | '0' |
*/
|
I recognize that the address of char '0' and '1' just offset 1bit.
No. They are offset one byte. The size of char is one byte and array elements are adjacent in virtual memory. String is an array.
|
70,347,533 | 70,348,572 | "warning C4172: returning address of local variable or temporary" when returning reference to static member | I have this class with a function that returns a value. For complicated reasons, the value needs to be returned as a const reference.
(minimal working example contains an int array, real code has more complex objects, hence the reference)
class Foo
{
public:
static constexpr const int OUT_OF_BOUNDS_VALUE = -9999;
const int& ret(int i) const { return i < 0 || i > 4 ? OUT_OF_BOUNDS_VALUE : test[i]; }
private:
int test[5] = {0, 1, 2, 3, 4};
};
This gives me warning C4172: returning address of local variable or temporary in VS2015 and it doesn't even compile with GCC.
Adding the line constexpr const int Foo::OUT_OF_BOUNDS; outside of Foo lets GCC compile just fine. VS2015 still gives the warning.
Removing constexpr and splitting the declaration from the definition fixes the warning, but why should I have to do that?
OUT_OF_BOUNDS isn't local, and it isn't temporary, right? Does it not have an address when it is defined and declared inside of the class definition?
See the warning live: https://godbolt.org/z/fv397b9rr
| The problem is that in C++11, we have to add a corresponding definition for a static constexpr declaration of a class' data member. This is explained in more detail below:
C++11
class Foo
{
public:
static constexpr const int OUT_OF_BOUNDS_VALUE = -9999; //THIS IS A DECLARATION IN C++11 and C++14
//other members here
};
In the above code snippet(which is for C++11,C++14), we have a declaration of the static data member OUT_OF_BOUNDS_VALUE inside the class. And so, in exactly one translation unit we have to provide a corresponding definition. Otherwise you'll get a linker error which can be seen here.
That is, in exactly one translation unit we should write:
constexpr const int Foo::OUT_OF_BOUNDS;//note no initializer
C++17
class Foo
{
public:
static constexpr const int OUT_OF_BOUNDS_VALUE = -9999; //THIS IS A DEFINITION IN C++17
//other members here
};
In the above code snippet(which is for C++17) we have a definition of the static data member OUT_OF_BOUNDS_VALUE inside the class. So since C++17, we don't have to provide the definition of OUT_OF_BOUNDS_VALUE anywhere else since we already have a definition for it inside the class.
The warning that you're getting with MSVC seems to be a bug.
|
70,347,787 | 70,357,225 | How to add a symbol to cmake, in debug mode only? | I want the following code to only be compiled in debug mode
main.cpp
#ifdef __DEBUG__
int a=1;
std::cout<<a;
#endif
adding the following to cmake
add_compile_options(
"-D__DEBUG__"
)
or
add_compile_options(
"$<$<CONFIG:DEBUG>:-D__DEBUG__>"
)
just doesn't seem to do anything.
How can I achieve desired behavior?
| Option 1: NDEBUG
CMake already defines NDEBUG during release builds, just use that:
#ifndef NDEBUG
int a=1;
std::cout<<a;
#endif
Option 2: target_compile_definitions
The configuration is spelled Debug, not DEBUG. Since you should never, ever use directory-level commands (like add_compile_options), I'll show you how to use the target-level command instead:
target_compile_definitions(
myTarget PRIVATE "$<$<CONFIG:Debug>:__DEBUG__>"
)
There's no need to use the overly generic compile options commands, either. CMake already provides an abstraction for making sure that preprocessor definitions are available.
|
70,348,102 | 70,348,122 | For Loop is not iterating for a third time? (C++) | Question: Why is my for loop not iterating for the third time?
What I noticed: In the for loop statement below, removing the if-else statement allowed me to print i from 0-2 and the "1" three times.
for (size_t i {0}; i < user_input.length(); ++i) {
cout << i << endl;
cout << user_input.length() << endl;
string the_spaces;
string the_line;
for (size_t b {i}; b < (user_input.length() - 1); ++b) {
the_spaces += " ";
}
for (size_t k {0}, y {i+1}; k < y; ++k) {
the_line += user_input[k];
}
if (i >= 1) {
cout << "Bob";
for (size_t z {i - 1}; z >= 0; --z) {
the_line += user_input[z];
}
}
else {
cout << "Beb" << endl;
}
cout << "1" << endl;
}
Output:
0 // i
3 // the user_input.length
Beb // output from if-else
1 // 1 printed at the end of the for loop expression
1 // i (2nd iteration)
3 // the user input.length
the code ends here... Neither printing Beb or Bob, as well as, the "1" from cout << "1" << endl; on the 2nd & 3rd iteration.
| z >= 0 is always true since z is an unsigned type.
Your program therefore loops. Although there are other solutions, using a long long rather than a std::size_t as the loop index is probably the simplest.
b < (user_input.length() - 1) is also problematic if user_input is empty. Use
b + 1 < user_input.length()
instead.
|
70,348,873 | 70,351,288 | Problem with python and arduino in pyserial | I wrote this code to print the sensor values in Python, but the problem is that the soil_sensor prints twice.
This is the code in the Arduino :
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 8
#define DHTTYPE DHT11
int msensor = A0;
int msvalue = 0;
int min = 0;
int max = 1024;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
pinMode(msensor, INPUT);
dht.begin();
}
void loop() {
msvalue = analogRead(msensor);
float percentage = (float)((msvalue - min) * 100) / (max - min);
percentage = map(msvalue, max, min, 0, 100);
Serial.print("r ");Serial.println(percentage);
int h = dht.readHumidity();
int t = dht.readTemperature();
Serial.print ("h ");
Serial.println (h);
Serial.print ("c ");
Serial.println (t);
delay(2000);
}
And this is the code in Python :
from time import sleep
import serial
arduinoP1 = serial.Serial(port="/dev/ttyUSB0", baudrate=9600)
def rtot():
arduino_data = arduinoP1.read(6)
str_rn = arduino_data.decode()
sleep(1)
return str_rn
for x in range(3):
i = rtot()
if "r" in i:
v1 = int(float(i[1:5].strip('\\r\\nr')))
print(v1, 'soil_sensor')
if "c" in i:
print(i[1:2], 'temperature_sensor')
if "h" in i:
v3 = int(i[2:4])
print(v3, 'Humidity_sensor')
As you can see, the soil sensor is repeated twice :
soil sensor is repeated twice
I want the values to be displayed correctly and in the form of numbers
| The first thing you should notice is that sending numbers throug the serial interface will result in different string lenghts depending on the number of digits.
So reading a fixed number of 6 bytes is not a good idea. (actually this is almost never a good idea)
You terminate each sensor reading with a linebreak. So why not use readline instead of read[6].
Here v1 = int(float(i[1:5].strip('\\r\\nr'))) you're trying to remove \r, \n and r from the received string. Unfortunately you escaped the backslash so you're actually stripping \, r and n.
\r is actually something where you need the backslash to represent the carriage return character. Don't escape it!
In the first run loop() will send something like:
r 0.00\r\nh 40\r\nc 25\r\n
So the first 6 bytes are r 0.00. So i[1:5] is 0.0.
As you see there is nothing to escape. Also 5 is excluded so you would have to use i[2:6] to get 0.00. But as mentioned above using fixed lenghts for numbers is a bad idea. You can receive anything between 0.00 and 100.00 here.
So using readline you'll receive
r 0.00\r\n
The first and last two characters are always there and we can use [2,-2] to get the number inbetween regardless of its length.
|
70,348,888 | 70,349,018 | Tuple of Jsoncpp functions | I am currently working with some config files, and I wanted to map options with configuration functions. So far, I have this working code:
std::unordered_map<std::string, void (Model::*)(int)> m_configMap =
{
{ "threshold", &Model::setThreshold }
};
Now, as you may very well notice, this approach would not work if the input parameters were different, so I thought of adding the a parser like so (with the Jsoncpp library):
std::unordered_map<stsd::string, std::tuple<void(Model::*)(std::any), std::any(Json::Value*)()>> m_configMap =
{
{ "threshold", {&Model::setThreshold, &Json::Value::asInt}}
};
Now, this did not work,as it was giving me an error in the brace initialiser list saying that it could not convert types. I didnt quite understand, so I tried an smaller example:
std::tuple<void(Model::*)(int), Json::Int (Json::Value::*)(void)> foo =
{&Model::setThreshold, &Json::Value::asInt };
And this is not working either. However, if I change the Json part for a string, it will work.
I am not sure of what is wrong with this, and I was wondering if someone saw something that I'm missing.
Thank you very much in advance
| Looks like you're not refering to an instance of Model, or the member function of Model is not static. I don't know about the JSON part but this should get you started. If you have questions let me know.
#include <iostream>
#include <functional>
#include <string_view>
#include <unordered_map>
struct Model
{
public:
void setTreshold(int value)
{
std::cout << "treshold set to " << value << "\n";
}
};
int main()
{
Model model;
// I prefer using string_view over string for const char* parameters
// I also prefer using std::function over function pointers
std::unordered_map<std::string_view, std::function<void(int)>> m_configMap
{{
// the function should refer to an instance of Model, so use a lambda
// not a direct function pointer
{"threshold", [&](int value) { model.setTreshold(value); } }
}};
auto fn = m_configMap["threshold"];
fn(42);
return 0;
}
|
70,349,958 | 70,350,089 | Use of ternary operator instead of if-else in C++ | I just came across the following (anonymized) C++ code:
auto my_flag = x > threshold;
my_flag ? do_this() : do_that();
is this a standard C++ idiom instead of using if-else:
if (x > threshold)
{
do_this();
}
else
{
do_that();
}
Even though it's only two lines, I had to go back and re-read it to be sure I knew what it was doing.
| No. In general the conditional operator is not a replacement for an if-else.
The most striking difference is that the last two operands of the conditional operator need to have a common type. Your code does not work eg with:
std::string do_this() {return {};}
void do_that() {}
There would be an error because there is no common type for void and std::string:
<source>: In function 'int main()':
<source>:15:22: error: third operand to the conditional operator is of type 'void', but the second operand is neither a throw-expression nor of type 'void'
15 | my_flag ? do_this() : do_that();
| ~~~~~~~^~
Moreover, the conditional operator is often less readable.
The conditional operator can be used for complicated in-line initialization. For example you cannot write:
int x = 0;
int y = 0;
bool condition = true;
int& ref; // error: must initialize reference
if (condition) ref = x; else ref = y; // and even then, this wouldn't to the right thing
but you can write
int& ref = condition ? x : y;
My advice is to not use the conditional operator to save some key-strokes compared to an if-else. It is not always equivalent.
PS: The operator is called "conditional operator". The term "ternary operator" is more general, like unary or binary operator. C++ just happens to have only a single ternary operator (which is the conditional operator).
|
70,350,208 | 70,352,742 | C++ Returning a member from one of 2 structs using macros or templates | I am working on a plugin that runs inside a host program against a proprietary PDK. At times there will be breaking changes in the PDK, so my code uses wrapper classes that allow it to work with more than one version of the host while encapsulating the changes from version to version.
Here is a very simplified example that illustrates the kind of issue I would like to address. Of course, I'm dealing with many more members that 2.
struct DataV1 // I cannot modify this
{
int a;
float b;
};
struct DataV2 // I cannot modify this
{
float b;
int a;
long c;
};
class DataWrapper // my class
{
private:
bool _forV1; // determined at run-time
DataV1 _dataV1;
DataV2 _dataV2;
public:
DataWrapper(); // initializes _forV1
int GetA() const;
void SetA(int value);
float GetB() const;
void SetB(float value);
long GetC() const { return _dataV2.c } // only exists in v2
void SetC(long value) { _dataV2.c = value; } // only exists in v2
};
I would like to avoid duplicating in every getter and setter the logic that chooses the member from one version of the struct or the other. Note that while the order of members is rearranged, the types and member names are the same. I came up with this macro:
#define DATA_ACCESS(MEMBER) const_cast<decltype(_dataV1.MEMBER)&>(([&]() -> const decltype(_dataV1.MEMBER)& \
{ return (_forV1) ? _dataV1.MEMBER : _dataV2.MEMBER; })())
This allows for a somewhat elegant implementation of the property accessor functons:
int GetA() const { return DATA_ACCESS(a); }
void SetA(int value) { DATA_ACCESS(a) = value; }
float GetB() const { return DATA_ACCESS(b); }
void SetB(float value) { DATA_ACCESS(b) = value; }
I am posting this question to see if anyone has a better idea, especially an idea that doesn't involve a macro. Thanks.
| With std::variant, you might do something like:
class DataWrapper // my class
{
private:
std::variant<DataV1, DataV2> data;
public:
DataWrapper(); // initializes _forV1
int GetA() const { return std::visit([](auto& arg){ return arg.a; }, data); }
void SetA(int a) const { std::visit([&a](auto& arg){ arg.a = a; }, data); }
// ...
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.