question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,097,842 | 69,098,234 | compile dependencies into a library itself | I want to provide a large library I programmed (further called "my lib") to another developer who is building a larger application (further called "target application"). My lib is under very experimental development and I may change dependencies, versions of those, etc. quite often. To call the developer of the target application every other week to change dependencies looks like an unclean option to me. It would be very nice, to just exchange a single (or a couple of) file(s) that include all of my dependencies, which brings me to my question:
Is it possible for me to compile all of my dependencies into the library I'm building in such a way that the developer of the target application will not have to include the header files, dlls libs, etc. of the dependencies of my lib?
Something similar is possible for executable files, where staticly linked libraries will be compiled into the executable.
Is something similar possible for this use-case? I say "library" on purpose because I dont care if it results in a DLL or staticly linked file.
Thanks in advance!
| The real answer is this: use a proper dependency manager.
Ensure you have a proper build system setup where no matter the usage requirement change, no changes are required for projects down the line. Coupled with a dependency manager, it won't matter how your usage requirement are: the user will only update the library and the tools take care of the rest.
CMake exported targets are excellent for this kind of purpose. A proper package manager such as vcpkg can completely handle this with a custom repository.
Now for the boring and unoptimal answer.
What you could do is compile your library in a dynamic library. Only update the DLL and the headers and ask statically linked libraries will be updated too, since they are statically linked into the DLL.
However, when doing this, you expose yourself to some problems:
First, you'll most likely have to ship you libraries headers too, or even compile definition. This might change usage requirements of your library. To hide all of this, you may need to wrap all your classes in pimpl wrappers. This will prevent you from using many features, such as templates or constexpr.
Second, the moment you ship your library as a DLL, you expose yourself to ABI. Users will attempt to only update the DLL without recompiling, and any ABI compatibility issues will be brought up. Adding a virtual function, changing the name of a function, adding a member to a class, changing the meaning or the result of a function, even fixing a bug can result in an ABI break.
|
69,098,362 | 69,098,580 | Why allocate_at_least() in C++23? | According to cppref:
std::allocator<T>::allocate_at_least
Allocates count * sizeof(T) bytes of uninitialized storage, where
count is an unspecified integer value not less than n, by calling
::operator new (an additional std::align_val_t argument might be
provided), but it is unspecified when and how this function is called.
Then, this function creates an array of type T[count] in the storage
and starts its lifetime, but does not start lifetime of any of its
elements.
However, I think the already existing std::allocator<T>::allocate can do the same thing.
Why do we need std::allocator<T>::allocate_at_least in C++23?
| allocate_at_least does not do the same thing as allocate. Compare (allocate):
Allocates n * sizeof(T) bytes of uninitialized storage...
with (allocate_at_least):
Allocates count * sizeof(T) bytes of uninitialized storage, where count is an unspecified integer value not less than n...
Moreover, allocate returns:
Pointer to the first element of an array of n objects of type T...
While allocate_at_least returns:
std::allocation_result<T*>{p, count}, where p points to the first element of an array of count objects of type T...
The caller thus gets the information about the actually allocated size.
The motivation can be found in P0401R6; Section Motivation:
Consider code adding elements to vector:
std::vector<int> v = {1, 2, 3};
// Expected: v.capacity() == 3
// Add an additional element, triggering a reallocation.
v.push_back(4);
Many allocators only allocate in fixed-sized chunks of memory, rounding up requests. Our underlying heap allocator received a request for 12 bytes (3 * sizeof(int)) while constructing v. For several implementations, this request is turned into a 16 byte region.
|
69,098,424 | 69,098,838 | Is this the right way? How to get Hex value into a char array? | I need following char packet[] = {0x00,0x14}; to send over a TCP/IP, this is the only way I got it to work. With that char I would send the number 20, another possible example would be char packet[] = {0x4e,0x20}; that would be 20000. I am Starting to think that I am approaching this completely wrong.
With this code I can print the Hex value of an Int out.
#include <iostream>
using namespace std;
int main() {
int num, temp, i = 1, j,k=1, r;
char hex[50] = {};
char paket[7] = {'0','x'};
cout << "Input?";
cin >> num;
temp = num;
while (temp != 0) {
r = temp % 16;
if (r < 10)
hex[i++] = r + 48;
else
hex[i++] = r + 55;
temp = temp / 16;
}
cout << i << endl;
cout << "\nHex = ";
for (j = i; j > 0; j--) {
cout << hex[j];
switch (k)
{
case 1:
paket[2] = { hex[j] };
break;
case 2:
paket[3] = { hex[j] };
break;
case 3:
paket[4] = { hex[j] };
break;
case 4:
paket[5] = { hex[j] };
break;
}
k++;
}
cout << endl << paket;
return 0;
This part is how I am trying to get the format I need, but sadly it's not working.
switch (k)
{
case 1:
paket[2] = { hex[j] };
break;
case 2:
paket[3] = { hex[j] };
break;
case 3:
paket[4] = { hex[j] };
break;
case 4:
paket[5] = { hex[j] };
break;
}
k++;
| If you just want to convert a number than can be expressed in 16-bits into an array of 2 bytes using network byte order as you imply.
int num = 20000; // or any number for that matter
char packet[2];
packet[0] = (num & 0xff00)>>8; // 0x4E
packet[1] = (num & 0x00ff); // 0x20
Done.
Alternatively, most network programming uses memcpy to byte-pack integers into byte arrays:
uint16_t num = 20000;
char packet[2];
memcpy(packet, &num, 2);
The only problem is that on Little Endian platforms, such as all Intel chips, the above code will write {0x20, 0x4E} into the array. The bytes will be in the wrong order. There's a helper function that swaps those bytes out called htons. The header files to import htons and similar functions vary between OS platform, but is available everywhere.
uint16_t num = 20000;
char packet[2];
num = htons(num); // swaps bytes on little endian, no-op on big-endian
memcpy(packet, &num, 2);
|
69,098,501 | 69,101,333 | C++. How to sort by module with saving the original order of elements | I'm trying to sort element in vector by module with the condition that the initial order of equal (by module) elements does not change. Logic tells me that the comparator should take less than or equal to save the original order.
std::sort(v.begin(), v.end(), [](int a, int b) {
return abs(a) <= abs(b);
});
But with and example of 1 -1 1 -1 my compiler return -1 1 -1 1. Unfortunately it saves order with less than sign(I don't understand why).
Decided that std::sort is not stalbe, I tried to use std::stable_sort and with and example of -1 1 1 -1 -1 it reversed elements in order -1 -1 1 1 -1 - Although I expected that the order would not change with a sign less than or equal.
What am I wrong about? Is there a lambda that is guaranteed to preserve the order of the elements?
|
What am I wrong about?
Your programs had undefined behaviour, because std::sort and std::stable_sort require a strict weak order, which <= isn't. Importantly when you compare an element to itself, the comparison must return (a value that converts to) false.
If you want a stable sort, use std::stable_sort with a valid Compare
std::stable_sort(v.begin(), v.end(), [](int a, int b) {
return abs(a) < abs(b);
});
|
69,098,826 | 69,115,911 | Signed integer overflow undefined behavior | In this question, there is this answer stating
Signed integer overflow is undefined behaviour
but it gives no reference to the C++ standard, so I tried to look it up myself in ISO/IEC 14882 (sixth edition 2020-12). In § 7.7 on page 148 I found (5.7)
an operation that would have undefined behavior as specified in Clause 4 through Clause 15 ^84;
referring to footnote 84 (76 in the draft) telling me
This includes, for example, signed integer overflow (7.2), certain pointer arithmetic (7.6.6), division by zero (7.6.5), or certain shift operations (7.6.7).
Next I searched for "undefined" in chapter 7.2 and I just got 7.2.1 (11) and (11.3) and 7.2.2 (1) but I either don't understand these sentences or they are not related to signed integer overflow.
Is that reference in footnote 84 incorrect? Should it have referred to 7.1 (4) instead?
If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.
If the reference is correct, could someone explain in simple words where and how 7.2 makes signed overflow undefined behavior?
| Since a pull request was opened for this case, it seems that the reference to chapter 7.2 was wrong and it should have been 7.1 instead.
|
69,098,916 | 69,104,400 | Range-v3, how to access a range of a range value individually (group_by function) | I'm using range-v3 by Eric Niebler and using the ranges::views::group_by function.
In the documentation for group_by it says: "Given a source range and a binary predicate, return a range of ranges where each range contains contiguous elements from the source range such that the following condition holds: for each element in the range apart from the first, when that element and the first element are passed to the binary predicate, the result is true. In essence, views::group_by groups contiguous elements together with a binary predicate."
So, it returns a range and ranges. My question is how do I access the range of ranges individually? I've tried all the using ways of accessing ranges: p[0].first, p.at(0).first, p.begin.first etc. but no joy.
I have the following code:
#include "https://raw.githubusercontent.com/HowardHinnant/date/master/include/date/date.h"
#include <chrono>
#include <fmt/format.h>
#include <iostream>
#include <map>
#include <range/v3/all.hpp>
using namespace date;
template <typename TimePoint, typename Minutes>
constexpr auto candle_start(const TimePoint timestamp, const Minutes timeframe)
-> TimePoint {
using namespace std::chrono;
const auto time =
hh_mm_ss{floor<minutes>(timestamp - floor<days>(timestamp))};
return timestamp - (time.minutes() % timeframe);
}
auto main() -> int {
{
using namespace std::chrono;
using namespace std::chrono_literals;
const auto tp_now = std::chrono::system_clock::from_time_t(0);
const auto m =
std::map<system_clock::time_point, double>{{tp_now + 0min, 1.1},
{tp_now + 1min, 2.2},
{tp_now + 2min, 3.3},
{tp_now + 3min, 4.4},
{tp_now + 4min, 5.5},
{tp_now + 5min, 6.6},
{tp_now + 6min, 7.7},
{tp_now + 7min, 8.8},
{tp_now + 8min, 9.9},
{tp_now + 9min, 10.10},
{tp_now + 10min, 11.11},
{tp_now + 11min, 12.12},
{tp_now + 12min, 13.13},
{tp_now + 13min, 14.14}};
const auto timeframe = 2min;
const auto same_candle = [timeframe](const auto &lhs, const auto &rhs) {
return candle_start(lhs.first, timeframe) ==
candle_start(rhs.first, timeframe);
};
auto p = m
| ranges::views::reverse
| ranges::views::group_by(same_candle);
// How do I access the range of range values individually?
std::cout << p[0].first << " = " << p[0].second;
return 0;
}
and a play area is given here.
| p isn't a random access range (it can't be), so there isn't going to be support for indexing (i.e. [0]). And then p isn't a range of pairs, it's a range of range of pairs.
All views have a front() member function that they inherit from view_interface so if you want to print the first and second members of the first subrange of the first range, you can do:
std::cout << p.front().front().first << " = " << p.front().front().second;
Or you can use iterators, as usual.
fmt also supports formatting whole ranges, so if you're looking to just debug, that's probably your best bet:
fmt::print("{}\n", p);
You'll need to include fmt/ranges.h for this support and fmt/chrono.h for chrono-specific formatters.
|
69,099,783 | 69,099,981 | How to encapsulate a memory-mapped file into a std::vector? | In C++, on Linux, after I open a file with open() and then memory-map it with mmap(), I am given a void* that I can typecast to e.g. char* and read as desired.
But, suppose I want to use std::vector to access that data. How could I accomplish that?
At first I thought I could make a custom allocator for my std::vector. But I see two problems with that:
Its allocate() method will only receive a size argument. That is insufficient, as it also needs to know the already-mapped address, rather than allocating a new one (as allocators usually do.)
Its deallocate() method -- to do this correctly -- would need to both unmap the buffer (easy, once #1 above is solved,) and close() the file descriptor (hard, since it has no way of knowing that value.)
I thought about maybe storing this metadata (existing mapped address, and file descriptor) in a known place to be referenced by my custom allocator, but that would not be thread-safe without complicating things with TLS.
Is the above possible some way? Or ill-advised (if so, please explain)? Is there perhaps some other standard-library class that would serve my purpose?
My reason for wanting to do this, is to avoid a raw/POD pointer in a class that interprets the binary data in that memory-mapped region.
|
Is there perhaps some other standard-library class that would serve my purpose?
Yes: std::span is a wrapper that provides container like access without ownership.
|
69,100,088 | 69,107,442 | Want to put binary data of images into RocksDB in C++ |
I'm trying to save binary data of images in Key-Value Store
1st, read data using "fread" function. 2nd, save it into RocksDB. 3rd, Get the data from RocksDB and restore the data into form of image.
Now I don't know whether I have problem in 2nd step of 3rd step.
2nd step Put
#include <iostream>
#include <string.h>
#include "rocksdb/db.h"
DB* db;
Options options;
options.create_if_missing = true;
Status s = DB::Open(options, <DBPath>, &db);
assert(s.ok());
//read image
FILE* file_in;
int fopen_err = fopen_s(&file_in, <input_file_path>, "rb");
if (fopen_err != 0) {
printf(input_file_path, "%s is not valid");;
}
fseek(file_in, 0, SEEK_END);
long int file_size = ftell(file_in);
rewind(file_in);
//malloc buffer
char* buffer = (char*)malloc(file_size);
if (buffer == NULL) { printf("Memory Error!!"); }
fread(buffer, file_size, 1, file_in);
//main func
db->Put(WriteOptions(), file_key, buffer);
assert(s.ok());
fclose(file_in);
free(buffer);
buffer = NULL;
delete db;
3rd step Get
#include <iostream>
#include <string.h>
#include "rocksdb/db.h"
DB* db;
Options options;
options.create_if_missing = true;
Status s = DB::Open(options, <DBPath>, &db);
assert(s.ok());
//main func
std::string file_data
s = db->Get(ReadOptions(), file_key, &file_data);
assert(s.ok());
//convert std::string to char*
char* buffer = (char*)malloc(file_data.size() + 1);
std::copy(file_data.begin(), file_data.end(), buffer);
//restore image
FILE* test;
fopen_s(&test, "test.jpg", "wb");
fwrite(buffer, file_data.size(), 1, test);
fclose(test);
free(buffer);
delete db;
The output image is not valid, and if I convert jpg to txt, I only get "???".
I tried on BerkeleyDB in the same process, and I succeed to restore image.(I think it's because of Dbt class of BerkeleyDB)
I don't know where the data get crashed. Did I missed some options or process...?
| char* buffer = ...
db->Put(WriteOptions(), file_key, buffer);
How is RocksDB supposed to know the length of the buffer? When passing in a char* here, it is assumed to be a nul-terminated C string using the Slice(char *) implicit conversion. Nul-terminated C strings cannot be used for binary data because the data will be cut off at the first zero byte.
Although some RocksDB APIs are not up to modern C++ standards (for API compatibility), it is written for use with C++. Nul-terminated char *, FILE, fseek etc. are from C and cause lots of difficulty when attempting to interact with C++. If buffer were std::string, this bug would be fixed because the Slice(std::string) implicit conversion is very safe.
Other bugs:
Failure to re-assign s for the db->Put
Failure to abort on error cases with printf
Better to call DB::Close(db) before delete to check status, as there could be a background error
Not checking for error in fread
Performance/clarity issue:
In 3rd step, no need to create char *buffer and copy in std::string file_data to it. file_data.data() and file_data.size() give you access to the underlying char buffer if needed (but using C++ APIs is better).
|
69,100,233 | 69,104,124 | Can't find 'Show Call Hierarchy' in VSCode | When I right click a function, there's no 'Show Call Hierarchy' or 'Peek Call Hierarchy'
option whatsoever. My popup menu looks like this
Then I tried Typing 'Show All Hierarchy' in command palette. This command does exist, but only gives a 'No Result' window after hitting enter.
So I went to Keyboard Shortcuts page, and it looks like this
My questions are,
Why can't I find 'Call Hierarchy' in popup menu while every tutorial online claims that I should have found it at this point.
What does 'When' field in Keyboard Shortcut page mean? Am I missing any 'CallHierarchyProvider'?
Addtional info:
VSCode version 1.60, having C/C++ and Emacs Keymap extensions installed. Tried VSCode on both MacOS and Ubuntu, issue remains the same. The code base I'm currently viewing is configured with CMake.
Any help is appreciated, thanks.
| When a feature like that is added to VSCode release notes or any other documentation, you should assume that it is initially only available for JavaScript/TypeScript,
Visual Studio Code show call hierarchy
That's very commmon because VSCode is just an editor providing the infrastructure (context menus and other visual elements), but the actual language feature is provided by the individual language extensions and their language servers.
In your case, the C++ extension and its language server might fall far behind to support such features.
|
69,100,444 | 69,100,665 | Raw pointer to shared_ptr bug | I'm working on a image treating application.
In summary, I have a byte buffer which stores the image data, so I can use this array to handle the image easily in wx widgets and OpenCV. I planned to store this byte buffer in a shared_ptr as it will be used in other instances of the same class along the execution.
With raw pointer it works properly, but whenever I tried to use shared_ptr I'm having an segmentation fault whenever passing this pointer to a function.
How can I pass it to this function without segmentation fault? it doesn't make sense to me this crashing
The bug is here
_dataSize = (size_t)len;
_originalData = std::make_shared<void*>(malloc(_dataSize));
if ( file.Read(_originalData.get(), _dataSize) != len )
on the last line of above code, I'm trying to pass the _original data pointer to Read function
Here's the full code, on the piece above, I just put the line that the bug is happening. On the full the code the bug is on src/Img.cpp file on line 18
Thank you
| _originalData.get() is a void**, not a void*.
To share ownership of that allocation, you need std::shared_ptr<void>, not std::shared_ptr<void*>. You also need to set the deallocation function, as it is undefined behaviour to delete a pointer that was malloced.
_originalData = std::shared_ptr<void>{ malloc(len), free }; // _originalData is a `std::shared_ptr<void>
if ( file.Read(_originalData.get(), len) != len )
Alternatively, since C++20, you could use a std::shared_ptr<char[]>, and not use malloc at all.
_originalData = std::make_shared_for_overwrite<char[]>{ len }; // _originalData is a `std::shared_ptr<char[]>
if ( file.Read(*_originalData, len) != len ) // implicit conversion of char* to void*
|
69,100,593 | 69,100,700 | memcpy - taking the address of temporary array error | I am working on Arduino and trying to change the elements of an array. Before setup, I initialized the array like this:
bool updateArea[5] = { false };
And then I wanted to change the array like this:
updateArea[0] => false,
updateArea[1] => true,
updateArea[2] => false,
updateArea[3] => false,
updateArea[4] => true
by using:
memcpy(&updateArea[0], (bool []) {false, true, false, false, true}, 5);
However, I get the "taking address of temporary array" error.
I also tried to initialize the array in setup and loop functions but get the same error.
| This sort of syntax is valid in C, but not in C++ - which is the language underlying the Arduino IDE.
But you have a few easy solutions:
Since you're willing to write out the array anyways, why not just:
bool updateArea[5] = {false, true, false, false, true};
You can declare the array as a non-temporary array and then pass it to memcpy:
static const bool newArray[5] = {false, true, false, false, true};
memcpy(updateArea, newArray, sizeof(updateArea));
If you can assume that sizeof(bool) == 1, then you can use this hacky solution:
memcpy(updateArea, "\x00\x01\x00\x00\x01", sizeof(updateArea));
which will copy the bytes directly.
|
69,100,653 | 69,102,524 | const inline std::map in header causes heap corruption at exit | I want to have const std::map in header as a global constant that will be used in other cpp-s. So I declared it as:
// header.h
const inline std::map<int, int> GlobalMap = { {1, 2}, {3, 4} };
However, if I include this header in multiple cpp-s, heap corruption happens at exit time because multiple destructors are run for the same memory address.
I've always assumed that inline const is a silver bullet for global non-literal constants. I've declared global std::string-s as const inline and it worked just fine.
So my questions are:
Why is this intended to happen? Doesn't it make const inline very error prone?
How do I properly declare global const std::map in C++17? And how can I ensure that only one global object would be created?
EDIT:
I can reproduce it on the following project in Visual Studio 2017 (/std:c++17, Debug x86)
file_1.h:
#pragma once
#include <map>
const inline std::map<int, double> GlobalMap = {{1, 1.5}, {2, 2.5}, {3, 3.5}};
void f1();
file_1.cpp:
#include "file_1.h"
void f1()
{
(void)GlobalMap;
}
main.cpp:
#include "file_1.h"
int main()
{
f1();
return 0;
}
| This looks like a Visual Studio bug: https://developercommunity.visualstudio.com/t/static-inline-variable-gets-destroyed-multiple-tim/297876
At the time of posting, the bug has status "Closed - Lower Priority", i.e. it is not fixed.
From the comment of the Microsoft representative:
If you still face this issue in our latest version, please report it as a new problem.
So I'd suggest filing a new problem with a repro-case.
|
69,100,704 | 69,104,561 | Unexpected/Incorrect Results while running SYCL/DPC++ code | I am a beginner in SYCl/DPC++. I want to print multiples of 10 but, instead of that, I am getting 0's in place of that.
I am using the USM (Unified Shared Memory) and I am checking the data movement in the shared memory and host memory implicitly. So I have created two Arrays and I have initialized and performing the operation on them. I can see the same results for both of them.
Here is my code; I don't understand where I went wrong.
#include <CL/sycl.hpp>
#include<iostream>
using namespace std;
using namespace sycl;
constexpr int n = 10;
int main() {
queue q;
int *hostArray = malloc_host<int>(n, q);
int *sharedArray = malloc_shared<int>(n, q);
for (int i = 0; i < n; i++)
hostArray[i] = i;
q.submit([&](handler &h) {
h.parallel_for(n, [=](id<1> i) {
sharedArray[i] = hostArray[i] * 10;
});
});
for (int i = 0; i < n; i++) {
hostArray[i] = sharedArray[i];
cout<<hostArray[i]<<" "<<sharedArray[i];
cout<<"\n";
}
cout<<"\n";
return 0;
}
Expected Results:
0 0
10 10
20 20
30 30
40 40
50 50
60 60
70 70
80 80
90 90
Actual Output:
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
| You are missing a barrier between the submission of the queue and the for loop in the host code.
Although it is true that an USM shared memory allocation is visible on the host and the device, there is no guarantees that the command group you have submitted to the queue will execute before the for loop in the host: Submissions to queues execute asynchronously w.r.t to the calling thread.
Updated code below:
#include <CL/sycl.hpp>
#include<iostream>
using namespace std;
using namespace sycl;
constexpr int n = 10;
int main() {
queue q;
int *hostArray = malloc_host<int>(n, q);
int *sharedArray = malloc_shared<int>(n, q);
for (int i = 0; i < n; i++)
hostArray[i] = i;
q.submit([&](handler &h) {
h.parallel_for(n, [=](id<1> i) {
sharedArray[i] = hostArray[i] * 10;
});
});
// Wait for completion of all previously submitted command groups
q.wait();
for (int i = 0; i < n; i++) {
hostArray[i] = sharedArray[i];
cout<<hostArray[i]<<" "<<sharedArray[i];
cout<<"\n";
}
cout<<"\n";
return 0;
}
|
69,100,745 | 69,106,103 | How to adjust source code highlighting in GDB cli? | I am using basic GDB CLI tool, no any TUI frontends. It highlights some parts of code with the same color as my terminal background making them indistinguishable. I know it is possible to disable source code highlighting but I would like to have it.
I didn't find much about this in documentation besides the fact that either GNU Source Highlight library, or Python Pygments package provide highlighting, but not a single word about how to check which of them GDB actually use or how to configure them and adjust colors.
| Edit esc.style in /usr/share/source-highlight/esc.style
GDB uses source-highlight which should not be confused with similar tool called just 'highlight' and provided by some distributions including Debian and Ubuntu. It is possilbe to check if GDB is actually linked with it: there should be --enable-source-highlight line in gdb --configuration output. It is documented in info source-highlight and is configured by .lang and .style files. esc means 'escape' and used for output in terminal, esc.style usage is hardcoded in GDB sources, it would be more correct to check terminfo and use esc256.style if appropriate, but it is written the way it is written.
|
69,101,123 | 69,101,170 | Using the !(not) operator when referring to a variable in a different class | I have created an object from the class HapticDevice and would like to use the !(not) operator when referring to device, but this leads it to change the variable name. What to do guys
Example code:
HapticsDevice haptic_device;
if (haptic_device.!device.get()) return;
| If you want to get haptic_device.device, NOT it, and then call get on the result of the not, it is (!haptic_device.device).get(). This is the same as (!(haptic_device.device)).get() since . has precedence over !. In fact, . has very high precedence.
I suspect you actually want !haptic_device.device.get() though which is the same as !(haptic_device.device.get()) i.e. call get() and then call ! on what get() returns.
|
69,101,279 | 69,101,467 | operator== in C++ struct | I'm trying to define an == operator in a structure:
typedef struct _tBScan {
QString strQuadpackNumbers;
uint uintBegin, uintEnd;
bool operator==(const struct _tBScan& a, const struct _tBScan& b) {
return (a.strQuadpackNumbers.compare(b.strQuadpackNumbers) == 0 &&
a.uintBegin == b.uintBegin && a.uintEnd == b.uintEnd);
}
} tBScan;
This won't compile, I get:
C2804: binary 'operator ==' has too many parameters
C2333: '_tBScan::operator ==' error in function: declaration: skipping function body
I'm using Qt 5.9.2 and MSVC 2015, I need to define this so I can use the QList compare function.
| When overloading an binary operator as a member function, the first parameter is this pointer. In the signature you have defined the operator==, it will take 3 arguments. However, it can only take two.
In you case I would recommend making it a non-member function.
typedef struct _tBScan {
QString strQuadpackNumbers;
uint uintBegin, uintEnd;
} tBScan;
bool operator==(const struct _tBScan& a, const struct _tBScan& b) {
return (a.strQuadpackNumbers.compare(b.strQuadpackNumbers) == 0 &&
a.uintBegin == b.uintBegin && a.uintEnd == b.uintEnd);
}
When you overload the, let's say, operator@ the expression _tBScan @ _smt is resolved into.
_tBScan.operator@(_smt);
When it's not a member function the expression is resolved into
operator@(_tBScan, _smt);
So the compiler searches the overload of either of them.
|
69,101,302 | 69,101,336 | Why does the below expression turn out to be true, asking for C++ specifically | #include <iostream>
using namespace std;
int main()
{
if(sizeof(int)> -1)
cout<<"ok";
else
cout<<"not ok";
return 0;
}
Isn't size of int supposed to be 4, which should be greater than -1.
| Two things:
sizeof(int) can be any positive integral value. (I've worked on a system where sizeof(char), sizeof(int) and sizeof(long) were all 1 and were all 64 bit types.)
The type returned by sizeof is an unsigned type. When comparing with -1, -1 is converted to an unsigned value, with a high magnitude. Almost certainly sizeof(int) will be less than that.
|
69,101,696 | 69,102,195 | How to get Version.Code in Android using C++? | I use native C++ with my Android project.
In Java or Kotlin we can use BuildVersion.Code to get the Android code from the Gradle file. How can I get this version code in C++?
| This is working for me:
jclass build_config_class = env->FindClass("com/example/app/BuildConfig");
jfieldID version_code_id = env->GetStaticFieldID(build_config_class, "VERSION_CODE", "I");
jfieldID version_name_id = env->GetStaticFieldID(build_config_class, "VERSION_NAME",
"Ljava/lang/String;");
int version_code = env->GetStaticIntField(build_config_class, version_code_id);
jstring version_name = (jstring) env->GetStaticObjectField(build_config_class, version_name_id);
You need to change com/example/app in the code to match your package name.
|
69,102,009 | 69,102,207 | Can't compile ftpupload.c | I'm trying to compile ftpupload.c with command g++ -o program ftpupload.c, but I get the following error:
ftpupload.c: In function ‘size_t read_callback(char*, size_t, size_t, void*)’:
ftpupload.c:57:50: error: invalid conversion from ‘void*’ to ‘FILE* {aka _IO_FILE*}’ [-fpermissive]
size_t retcode = fread(ptr, size, nmemb, stream);
^
In file included from ftpupload.c:22:0:
/usr/include/stdio.h:646:15: note: initializing argument 4 of ‘size_t fread(void*, size_t, size_t, FILE*)’
extern size_t fread (void *__restrict __ptr, size_t __size,
^~~~~
| This is compiling a C source file as C++. C++ is stricter when it comes to implicit conversions and does not allow an implicit conversion from a void* to any other pointer (source):
Pointer to object of any type can be implicitly converted to pointer to void (optionally cv-qualified); the pointer value is unchanged. The reverse conversion, which requires static_cast or explicit cast, yields the original pointer value: [..]
To resolve this, either use a C compiler or add a cast:
size_t retcode = fread(ptr, size, nmemb, static_cast<FILE*>(stream));
It is not recommended, but if this line needs to be bilingual C and C++, you could use a C-style cast:
size_t retcode = fread(ptr, size, nmemb, (FILE*) stream);
On a side note: ftpupload.c does not contain a standalone program and will not fully compile even with the cast. The best solution depends on why you'd like to compile this file in the first place.
|
69,102,287 | 69,102,469 | Access class from another C++ file | So I have a "main.cpp" file which I have declared an object of my class player:
main.cpp:
#include "player.h"
Player player;
int main() {
//
player.update();
}
I would like to access this object from multiple different C++ files. However, I would like to do this without using the keyword extern as i'm trying to stay away from global variables.
Hope someone can help me with this.
Thanks in advance!
| Rather than write functions like
file1.cpp
#include "player.h"
extern Player player;
void doStuffToPlayer() {
player.update();
}
file2.cpp
#include "player.h"
#include "file1.h"
Player player;
int main() {
doStuffToPlayer();
}
You can instead write
file1.cpp
#include "player.h"
void doStuffToPlayer(Player & player) {
player.update();
}
file2.cpp
#include "player.h"
#include "file1.h"
int main() {
Player player;
doStuffToPlayer(player);
}
|
69,102,611 | 69,102,723 | Why is a narrowing conversion from int to float only needed if I brace-initialise an object? | I ran into what I think is a weird thing:
#include <vector>
int numqueues = 1;
std::vector<float> priorities{numqueues, 1.f };
//^^^ warning: narrowing conversion of numqueues from int to float
//std::vector<float> priorities(numqueues, 1.f );
//^^^ No warning or error. And it's not because it's parsed as a function declaration
// as I can call push_back in main.
int main()
{
priorities.push_back(1);// No narrowing conversion needed
}
I've tried this using a couple of compilers, this won't compile.
Edit: It's been said that the initializer_list takes priority, and that looks to be the case, but I tried to mimic std::vector and I don't get the narrowing conversion error in this example:
#include <vector>
#include <iostream>
#include <initializer_list>
template <typename T>
class MyVector
{public:
MyVector(size_t s, float f) {
std::cout << "Called constructor\n";
}
MyVector(std::initializer_list<T> init)
{
std::cout << "Called initializer list constructor\n";
}
};
int main()
{
MyVector<float> foo{ size_t(3), 2.f };
}
I've done exactly the same thing, initialised it with size_t and float, just like in the other example, this one compiles fine.
| In this declaration
std::vector<float> priorities{numqueues, 1.f };
the compiler uses the initializer list constructor.
vector(initializer_list<T>, const Allocator& = Allocator());
The narrowing conversion for initializer lists is prohibited.
In this declaration
std::vector<float> priorities(numqueues, 1.f );
the compiler uses the constructor that specifies the number of elements and their initializer.
vector(size_type n, const T& value, const Allocator& = Allocator());
From the C++ 14 Standard (8.5.4 List-initialization)
2 A constructor is an initializer-list constructor if its first
parameter is of type std::initializer_list or reference to possibly
cv-qualified std::initializer_list for some type E, and either
there are no other parameters or else all other parameters have
default arguments (8.3.6). [ Note: Initializer-list constructors are
favored over other constructors in list-initialization
and (13.3.1.7 Initialization by list-initialization)
1 When objects of non-aggregate class type T are list-initialized such
that 8.5.4 specifies that overload resolution is performed according
to the rules in this section, overload resolution selects the
constructor in two phases:
(1.1) — Initially, the candidate functions are the initializer-list
constructors (8.5.4) of the class T and the argument list consists of
the initializer list as a single argument.
(1.2) — If no viable initializer-list constructor is found, overload
resolution is performed again, where the candidate functions are all
the constructors of the class T and the argument list consists of the
lements of the initializer list.
Here is a demonstrative program
#include <iostream>
#include <initializer_list>
struct A
{
A( std::initializer_list<float> )
{
std::cout << "A( std::initializer_list<float> )\n";
}
A( size_t, float )
{
std::cout << "A( size_t, float )\n";
}
};
int main()
{
A a1 { 1, 1.0f };
A a2( 1, 1.0f );
return 0;
}
The program output is
A( std::initializer_list<float> )
A( size_t, float )
As for your appended question then (8.5.4 List-initialization)
7 A narrowing conversion is an implicit conversion
(7.3) — from an integer type or unscoped enumeration type to a
floating-point type, except where the source is a constant
expression and the actual value after conversion will fit into the
target type and will produce the original value when converted back to
the original type, or
So in this list initialization
MyVector<float> foo{ size_t(3), 2.f };
the constant expression size_t( 3 ) that fits into the type float is used.
For example if in the above demonstrative program you will write
size_t n = 1;
A a1{ n, 1.0f };
then the compiler should issue a message about narrowing conversion (at least the MS VS 2019 C++ compiler issues such an error message).
|
69,102,939 | 69,103,001 | How can I print the length of words stored in a string array in C++? | I am trying to get the length of the words which I have stored in a string array.First,I specify the number of words in an array using 'n'(input from user), then I take inputs from the user of the 'n' words they want to store. After that, I wish to print the length of a word.
Here is the code....
#include <iostream>
using namespace std;
int main(){
int n;
cout<<"enter no"<<endl;
cin>>n;
string A[n];
for(int i=0;i<n;i++){
cin>>A[i];
}
cout<<strlen(A[2])<<endl;
}
For example,
if inputs are:
3
leonardo
tom
brad
(They are written in separate lines)
then output should be :
4
which is length of brad.
But I get a strange error while execution of this code. Please suggest a way to do this , while taking inputs from the user in separate lines
| cin>>n;
string A[n];
The size of an array must be known at compile-time. Variable-length arrays (VLA) are not supported in C++ (also some compilers do as an extension). Use a container with dynamic allocation instead, like std::vector.
std::cin >> n;
std::vector<std::string> A(n);
And use A[2].size() instead of strlen(A[2]).
|
69,103,523 | 69,103,851 | Does gcc-8 on arm64 debian ignores friend operator<? | I want to compare two sets of objects. For the same code I get 2 different outputs on different machines.
The code is compiled with two different compilers. On the x86-64 machine i used gcc-11, on the aarch64 (raspberry pi4) machine i used gcc-8. I have to use the gcc-8 on the raspberry because it's in the official repositories.
Has anyone an idea why this happens? Have I missed something?
#include <iostream>
#include <set>
#include <memory>
class ClassA {
private:
::std::string id;
public:
explicit ClassA(::std::string id);
[[nodiscard]] ::std::string getId() const;
bool friend operator<(const ::std::shared_ptr<ClassA> &lhs, const ::std::shared_ptr<ClassA> &rhs);
};
ClassA::ClassA(::std::string id) : id{::std::move(id)} {}
::std::string ClassA::getId() const { return id; }
bool operator<(const ::std::shared_ptr<ClassA> &lhs, const ::std::shared_ptr<ClassA> &rhs) {
auto r = (lhs->id < rhs->id);
::std::cout << ::std::boolalpha << "Comparing lhs->id " << lhs->id << ", with rhs->id " << rhs->id
<< ". The result is " << r << ::std::endl;
return (lhs->id < rhs->id);
}
class ClassB {
public:
::std::set<::std::shared_ptr<ClassA>> members;
void add(::std::shared_ptr<ClassA> a);
};
void ClassB::add(::std::shared_ptr<ClassA> a) {
members.emplace(::std::move(a));
}
int main() {
::std::cout << "Create first set:" << ::std::endl;
auto firstContainer = ::std::set<::std::shared_ptr<ClassA>>{::std::make_shared<ClassA>("_3"),
::std::make_shared<ClassA>("_5")};
::std::cout << "Create second set:" << ::std::endl;
auto secondContainer = ::std::set<::std::shared_ptr<ClassA>>{::std::make_shared<ClassA>("_5"),
::std::make_shared<ClassA>("_3")};
auto b1 = ::std::make_shared<ClassB>();
auto b2 = ::std::make_shared<ClassB>();
::std::cout << "Fill first ClassB instance:" << ::std::endl;
for (const auto &r: firstContainer) {
b1->add(r);
}
::std::cout << "Fill second ClassB instance:" << ::std::endl;
for (const auto &r: secondContainer) {
b2->add(r);
}
auto result = ::std::equal(b1->members.begin(), b1->members.end(), b2->members.begin(),
[](const ::std::shared_ptr<ClassA> lhs, ::std::shared_ptr<ClassA> rhs) -> bool {
return lhs->getId() == rhs->getId();
});
::std::cout << ::std::boolalpha << "The result is: " << result << ::std::endl;
::std::cout << "First ClassB members" << ::std::endl;
for (const auto &r: b1->members) {
::std::cout << "Id " << r->getId() << ::std::endl;
}
::std::cout << "Second ClassB members" << ::std::endl;
for (const auto &r: b2->members) {
::std::cout << "Id " << r->getId() << ::std::endl;
}
return 0;
}
The x86-64 output.
Create first set:
Comparing lhs->id _3, with rhs->id _5. The result is true
Comparing lhs->id _5, with rhs->id _3. The result is false
Create second set:
Comparing lhs->id _5, with rhs->id _3. The result is false
Comparing lhs->id _3, with rhs->id _5. The result is true
Comparing lhs->id _3, with rhs->id _5. The result is true
Fill first ClassB instance:
Comparing lhs->id _5, with rhs->id _3. The result is false
Comparing lhs->id _3, with rhs->id _5. The result is true
Comparing lhs->id _5, with rhs->id _3. The result is false
Fill second ClassB instance:
Comparing lhs->id _5, with rhs->id _3. The result is false
Comparing lhs->id _3, with rhs->id _5. The result is true
Comparing lhs->id _5, with rhs->id _3. The result is false
The result is: true
First ClassB members
Id _3
Id _5
Second ClassB members
Id _3
Id _5
The aarch64 output:
Create first set:
Create second set:
Fill first ClassB instance:
Fill second ClassB instance:
The result is: false
First ClassB members
Id _3
Id _5
Second ClassB members
Id _5
Id _3
| The problem is here:
bool operator<(const ::std::shared_ptr<ClassA> &lhs, const ::std::shared_ptr<ClassA> &rhs)
The shared pointer has its own comparison operators which compares stored pointers. There is also owner_less which compares owned pointers (a specially constructed shared pointer can own one object but point to another, e.g. it can point to a member of the owned object).
If you need to compare the pointed-to objects, you should write a comparator doing just that, and pass it to the set as second template argument. Like:
struct my_ClassA_id_less {
bool operator() (const ::std::shared_ptr<ClassA> &lhs, const ::std::shared_ptr<ClassA> &rhs) {
// your comparison code here, as for operator<
}
};
::std::set<std::shared_ptr<ClassA>, my_ClassA_id_less> my_set;
|
69,103,714 | 69,103,941 | no viable overloaded '=' and inheritance | I have the following class structure but when I build, I keep getting the error:
error: no viable overloaded '='
p1 = new HumanPlayer();
~~ ^ ~~~~~~~~~~~~~~~~~
../Test.cpp:14:7: note: candidate function (the implicit copy assignment operator) not viable: no known conversion from 'HumanPlayer *' to 'const Player' for 1st argument; dereference the argument with *
class Player {
^
1 error generated.
class Player {
public:
void getMove(int player) {
cout << "Get move" << endl;
}
};
class HumanPlayer: public Player {
public:
void getMove(int player) {
cout << "Get Human move \n";
}
};
class MyClass {
public:
int mode;
Player p1;
MyClass() {
mode = 0;
cout << "Choose a mode: \n";
cin >> mode;
switch (mode) {
case 1:
p1 = new HumanPlayer();
break;
default:
break;
}
p1.getMove(0);
}
};
int main() {
MyClass c;
return 0;
}
I tried to change the Player p1; to Player* p1; and changed p1.getMove to p1->getMove but then it did not work correctly. It printed Get move instead of Get Human move.
| as commented above
p1 = new HumanPlayer();
is valid if p1 is declared as pointer, unlike java you can in c++ assign with and without the new keyword...
in your case declaring p1 as pointer will be ok
Player* p1{nullptr};
and later
p1 = new HumanPlayer();
|
69,104,065 | 69,104,116 | c++ set erase function not working properly with iterator | set<int> s = {1, 2, 3, 4};
auto it = s.begin();
while (it != s.end()) {
// this correct
s.erase(it++);
// this incorrect
s.erase(it);
it++;
}
why on top of code can running?
My understand of the order when my code running is:
When the erase function is executed, then iterator was deleted.
The chaotic iterators executing add, it behaviour is undefined.
But it running normal, So my problem is why it can running and these code have difference?
| The best way would be:
it = s.erase(it);
Your code with post-increment also works, but it is less transparent. To recall, post-increment version is semantically equivalent with the following snippet:
temp = it;
++it;
s.erase(temp);
As for your claims of ill-formed (second version) code "running", the code which has undefined behavior can be "running" or even seem to deliver expected results. This is the gist of undefined behavior. And the code which increments iterator which has been erased exhibits undefined behavior, as per std::set::erase documentation:
References and iterators to the erased elements are invalidated. Other
references and iterators are not affected
|
69,104,492 | 69,105,108 | Is there a simple way to do array differences and approximate array derivatives in C++? (Like the diff() function in matlab) | Matlab code I would like to translate into C++
X = [1 1 2 3 5 8 13 21];
Y = diff(X)
output : 0 1 1 2 3 5 8
https://www.mathworks.com/help/matlab/ref/diff.html
| C++ calls it std::adjacent_difference.
int X[8] = {1, 1, 2, 3, 5, 8, 13, 21};
int Y[8];
std::adjacent_difference( std::begin(X), std::end(X), std::begin(Y) );
Note that the first element of the destination is a direct copy of the source. The remaining elements are differences.
See it work on Compiler Explorer.
|
69,104,539 | 69,104,824 | How to convert string to const unsigned char* without using reinterpret_cast (modern approach) | I have variable input type const std::string&:
const std::string& input
Now I need to convert this to const unsigned char* because this is the input of the function.
Unitl now I have correct code for converting:
reinterpret_cast<const unsigned char*>(input.c_str())
This works well, but in clang I got a warning:
do not use reinterpret_cast [cppcoreguidelines-pro-type-reinterpret-cast]
What is the correct way to change a string or const char* to const unsigned char*?
|
What is the correct way to change a string or const char* to const unsigned char*?
The correct way is to use reinterpret_cast.
If you want to avoid reinterpret_cast, then you must avoid the pointer conversion entirely, which is only possible by solving the XY-problem. Some options:
You could use std::basic_string<unsigned char> in the first place.
If you only need an iterator to unsigned char and not necessarily a pointer, then you could use std::ranges::views::transform which uses static cast for each element.
You could change the function that expects unsigned char* to accept char* instead.
If you cannot change the type of input and do need a unsigned char* and you still must avoid reinterpret cast, then you could create the std::basic_string<unsigned char> from the input using the transform view. But this has potential overhead, so consider whether avoiding reinterpret_cast is worth it.
|
69,104,609 | 69,104,777 | std::numbers has not been declared - GCC 11.2 on Windows | I have GCC 11.2.0 installed on my Windows 10 machine (from here: https://winlibs.com/). I have updated the environment variable Path to C:\MinGW\bin
gcc version 11.2.0 (MinGW-W64 x86_64-posix-seh, built by Brecht Sanders)
I'm using VSCode with the C/C++ extension configured to use the correct compiler path.
I want to use a C++20 feature which is
std::numbers::sqrt2
Still I get an error telling me it doesn't know std::numbers
[Running] cd "c:\Users\XX\XX\" && g++
main.cpp -o main && "c:\Users\XX\XX\"main
main.cpp: In function 'double sin_x_plus_cos_sqrt2_times_x(double)':
main.cpp:15:41: error: 'std::numbers' has not been declared
15 | return std::sin(x) + std::cos( std::numbers::sqrt2 * x );
|
I've added the header #include <numbers>
What am I missing ?
| Default version of c++ standard for this version of gcc is C++17.
See this: https://godbolt.org/z/4Pjzd5r7s
Use
g++ main.cpp -o main -std=c++20
to force C++20
There is some support of C++20 in gcc, but it is simply to early to make it default standard.
|
69,104,959 | 69,108,626 | Missing POSIX and std symbols using MSYS2/MINGW-64 | I tried to port some C/C++ code from Linux to Windows. On Linux I am using GCC-10 for building, on Windows I am trying to use MSYS2/MINGW-64. I have never used MSYS2 before and I have few experience in porting Linux/POSIX code to windows.
Most of the (Qt) code is portable anway so I got non-trivial problems only in a few code lines. The following symbols turned out to be missing:
on_exit()
O_SYNC (used with open())
sync()
std::at_quick_exit()
I'm not startled about 1. because it is not portable.
However 2. and 3. are POSIX symbols and 4. is part of the C++11 standard library. Since MSYS2 docs say it is POSIX and GCC compatible I would have expected these symbols to be defined.
Why are these symbols missing?
Is there a way to replace the missing features (maybe using calls to the Windows API)?
| I don't think MinGW ever claimed full POSIX compatibilty, so the lack of O_SYNC and sync() is to be expected.
on_exit has a standard alternative std::atexit.
Judging by the comments under this question, at_quick_exit (and quick_exit itself) aren't provided by msvcrt.dll (the old Microsoft C runtime that MINGW64 uses). You can switch to the UCRT64 MSYS2 environment, which uses a more modern C runtime (ucrtbase.dll) that does have those functions.
|
69,105,039 | 69,105,145 | Compile error in full specialisation of function template | In the following program, I am trying to iterate over a list of types using a meta struct of types.
It compiles and works fine unless I specify template<> before the base print template definition.
/* example.cpp */
#include <iostream>
template<typename ...>
struct List{};
template<typename T,typename ...Rest>
void print(List<T,Rest ...> *) {
std::cout << typeid(T).name() << std::endl;
print((List<Rest ...> *)nullptr);
}
// uncommenting the next line creates compilation error
// template<>
void print(List<> *) {
}
int main() {
using L = List<int,double,float>;
print((L*)nullptr);
}
/* compile and execution
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
g++ -std=c++11 example.cpp
./a.out
i
d
f
*/
If I uncomment the template<> before the void print(List<> *) definition, g++ and clang++ both shows error.
// clang++ error
error.cpp:15:6: error: no function template matches function template specialization 'print'
void print(List<> *) {
^
error.cpp:8:6: note: candidate template ignored: failed template argument deduction
void print(List<T,Rest ...> *) {
^
1 error generated.
I don't understand why this form of full specialization is not working with template<> as template header? Am I missing some function template rule here?
Thanks!
Update:
The following program compiles and works well, when I added one more mandatory template parameter U.
#include <iostream>
template<typename ...>
struct List{};
template<typename U,typename T,typename ...Rest>
void print(U* , List<T,Rest ...> *) {
std::cout << typeid(T).name() << std::endl;
print((int*)nullptr, (List<Rest ...> *)nullptr);
}
// I dont understand, that `T` is missing here, but still compiles
template<typename U>
void print(U *,List<> *) {
}
int main() {
using L = List<int,double,float>;
print((int*)nullptr,(L*)nullptr);
}
I don't understand the cause of the error in the first program and the cause of no error in the second program.
| Your primary template is:
template<typename T, typename...Rest> void print(List<T, Rest...> *)
So one T and a pack.
template<> void print(List<> *) simply doesn't match.
You would have to have
template<typename...Ts> void print(List<Ts...> *) to allow your specialization.
Notice than with fold expression of C++17, it would simply be
template<typename ... Ts>
void print(List<Ts...>) {
((std::cout << typeid(Ts).name() << std::endl), ...);
}
int main()
{
using L = List<int, double, float>;
print(L{});
}
|
69,105,158 | 69,105,273 | Create variable that contains a string and std::endl, that can be used in output streams to std::cout | Using c++17
I have a header file colors.hpp to help me with colored output to stdout:
#pragma once
#include <string>
namespace Color
{
static const std::string yellow = "\u001b[33m";
static const std::string green = "\u001b[32m";
static const std::string red = "\u001b[31m";
static const std::string end = "\u001b[0m";
}
I often use it like this:
std::cout << Color::green << "some green text " << Color::end << std::endl;
I almost always put std::endl immediately after Color::end. I'd like to be able to achieve the same result (newline + buffer flush), but use only one variable - something like Color::endl.
I've only been able to come up with solutions that are string, which as far as I understand, will include the \n character but will not also force the flush to stdout.
static const std::string endl = std::ostringstream(static_cast<std::ostringstream &&>(std::ostringstream() << Color::end << std::endl)).str();
If I remove the .str() from the code above, then I can't do:
std::cout << Color::endl; because of
error: invalid operands to binary expression ('basic_ostream<char>' and 'const std::__1::basic_ostringstream<char>')
| std::endl is a function (actually function template), not an object. That means, if you want to replicate it, you need a function as well.
If you add this to Color:
template< class CharT, class Traits >
std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os )
{
return os << end << std::endl;
}
Then, when you use this:
std::cout << Color::green << "some green text " << Color::endl;
The Color::endl() function will get called, and then it can insert Color::end into the stream, and then std::endl to get the newline and flush behavior you want, as seen in this live example.
|
69,106,008 | 69,106,144 | Is it possible to force a class to be passed by reference or pointer (C++)? | I'm not entirely sure what to search for to see if this has been asked, so hopefully it isn't a duplicate.
Supposed I've written a class in C++. Is it possible, by way of constructors or some other internal (to the class) mechanism, to throw a compiler warning when the class is passed to a function not by reference.
The motivation behind this is simply to more forcefully control memory allocations. The class in question has several memory pointers that are allocated during class construction (as well as freed/allocated via various class member functions). The allocations are expensive and I want to warn the developer (well, let's be honest, I want to warn myself) of extraneous data copies. However, there are valid use cases for copying the class in other circumstances (might even be valid use cases for passing by value...though I cannot think of any that are unavoidable).
As an aside, the class can be passed by value - the class copy does work. However, I do not want it to be invoked unless it needs to be. Hence the compiler warning instead of an error.
A contrived example:
class doNotSilentCopy {
public:
doNotSilentCopy(size_t size) {
mysize = size;
dummy = (int*)malloc(mysize);
};
doNotSilentCopy() : doNotSilentCopy(0) {};
doNotSilentCopy(const doNotSilentCopy& rhs) {
this->mysize = rhs.mysize;
this->dummy = (int*)malloc(this->mysize);
};
~doNotSilentCopy(void) {
if (dummy) {
free(dummy);
dummy = nullptr;
mysize = 0;
}
};
int get(int index) {
return *(dummy + index);
};
private:
size_t mysize;
int* dummy;
};
int getDataBad(doNotSilentCopy cls, int index) {
return cls.get(index);
}
int getDataGood(doNotSilentCopy& cls, int index) {
return cls.get(index);
}
int main() {
doNotSilentCopy mycls(10);
int can_I_warn_about_this = getDataBad(mycls, 5);
int this_is_acceptable = getDataGood(mycls, 5);
return 0;
}
| While I was typing this "van dench" gave the short answer.
And what Ted Lyngmo also makes sense.
This is the answer in code if you want to be explicit.
class NonCopyableNonMoveable
{
public:
NonCopyableNonMoveable() = default;
NonCopyableNonMoveable(NonCopyableNonMoveable&&) = delete;
NonCopyableNonMoveable& operator=(const NonCopyableNonMoveable&) = delete;
~NonCopyableNonMoveable() = default;
NonCopyableNonMoveable Clone()
{
return NonCopyableNonMoveable(*this);
}
private:
NonCopyableNonMoveable(const NonCopyableNonMoveable&) = default;
};
void f(NonCopyableNonMoveable c)
{
}
int main()
{
NonCopyableNonMoveable l;
// f(l); // <== wont compile
auto copy_of_l = l.Clone();
return 0;
}
|
69,106,460 | 69,107,290 | Wrapping 2d grid indices | I have this function which i prototyped in python for navigating grid indexes. It works perfectly in python but due to the way the modulo operator handles negative numbers it falls down in c++. Can anyone suggest a modification that will make this work?
The function fails when coordinates nx and ny are negative.
int wrap_grid(int index, int x, int y, int nx, int ny) {
//first calculate positon on row by adding nx -
//assuming an infinite grid of indices (no limits or wrap)
int a = (index + (y * nx));
//then wrap around the width (x) of the row
int b = a % (x * y);
//now do column, calculate the bottom index of the column
int start = b - b % y;
//and the top index
int limit = b - b % y + y;
//now wrap the ny value around the columns
return start + (b + ny) % (limit - start);
}
EDIT: To explain function arguments
index is the index of a rectangular grid, like this:
col1
col2
col3
5
11
17
4
10
16
3
9
15
2
8
14
1
7
13
0
6
12
x is the width of the grid, in this case 3.
y is the height of the grid, in this case 6.
nx is the coordinate grid square offset, so nx = 1 is one grid square to the right, similar for ny=1 is one grid square 'upwards'.
The return value is the new index number after transforming index with the coordinates nx and ny.
EDIT: updated function based on jwezorek's approach. Note, the only effective change (function factors aside) are the comparison operators which must allow zero values.
int wrap_grid(int index, int rows, int columns, int offset_x, int offset_y) {
//index to grid coordinates always positive
int x = (index / rows) + (offset_x);
x = x >= 0 ? x : x + columns;
int y = (index % rows) + (offset_y);
y = y >= 0 ? y : y + rows;
//grids to coords
int column = x % columns;
column = column >= 0 ? column : column + columns;
int row = y % rows;
row = row >= 0 ? row : row + rows;
int bottom_of_column_index = column * rows;
return bottom_of_column_index + row;
}
| You just need a mod function that will only give you non-negative values. To just do it the straight-forward way is like below (after moving your code around for clarity).
#include <tuple>
#include <iostream>
int grid_coords_to_index(int cols, int rows, int x, int y) {
// wrap the coordinates...
int column = x % cols;
column = column >= 0 ? column : column + cols;
int row = y % rows;
row = row >= 0 ? row : row + rows;
int bottom_of_column_index = column * rows;
return bottom_of_column_index + row;
}
std::tuple<int,int> index_to_grid_coords(int cols, int rows, int index) {
// TODO: handle negatives correctly here too, if we cannot
// assume indices are positive.
return { index / rows, index % rows };
}
int wrap_grid(int initial_index, int cols, int rows, int x_offset, int y_offset) {
auto [x, y] = index_to_grid_coords(cols, rows, initial_index);
return grid_coords_to_index(cols, rows, x + x_offset, y + y_offset);
}
int main()
{
/*
5 11 17
4 10 16
3 9 15
2 8 14
1 7 13
0 6 12
index 9 is (1,3) so two to the left and one down should be 14 given wrapping
*/
std::cout << wrap_grid(9, 3, 6, -2, -1) << "\n";
}
|
69,106,519 | 69,118,255 | c++ destructor doesn't delete the object itself, what does? | Firstly, unless I've misunderstood it, a destructor frees up memory taken up by variables inside the object. In the below example it would delete the string pointed to by * str. That's ALL.
class StrPtr {
private:
string * str;
public:
StrPtr() : str(new string()) {}
~StrPtr() { delete str; }
void add(char c) { str->push_back(c); }
};
However, here's my confusion. If the destructor doesn't destroy the object itself. Does that mean:
After the for loop I have 10k StrPtr objects.
As soon as the for loop ends, the 10k StrPtr objects are deleted as they fall out of scope.
each time the someF() function finishes execution, the object is deleted, as it falls out of scope. Since this is where it was created. This is my thinking currently.
void someF() {
StrPtr s;
s.add('a');
}
int main() {
for (int i = 0; i < 10000; i++) {
someF();
}
}
| See option 3 on my question.
There are no memory leaks, there is never more than one StrPtr object in memory.
|
69,107,224 | 69,107,312 | How to convert variadic function arguments to array? | How to convert variadic function arguments to array?
I need something like this:
template <typename T>
struct Colordata
{
public:
T dataFirst;
T dataLast;
template <typename... Ta>
Colordata(Ta... args)
{
constexpr std::size_t n = sizeof...(Ta);
std::cout << n << std::endl;
dataFirst = (args..)[0];
dataLast = (args...)[n - 1];
return;
}
};
int main(int argc, char const *argv[])
{
auto a = Colordata<float>(1.0f, 2.2f, 3.3f, 4.3f, 5.5f);
return 0;
}
I tried to use variadic arguments as T args, ... and use functions from stdarg.h but then I can't get the count of arguments.
| You can't convert a parameter pack into an array. You could create an array from one, but that would copy, and that would be wasteful. Instead, we can "convert" the parameter pack into a tuple of references, and then use get to index into that tuple. That would look like
template <typename... Ta>
Colordata(Ta... args)
{
constexpr std::size_t n = sizeof...(Ta);
static_assert(n >= 1, "must pass at least one argument");
std::cout << n << std::endl;
auto& tuple = std::tie(args...);
dataFirst = std::get<0>(tuple)
dataLast = std::get<n - 1>(tuple);
}
|
69,107,280 | 69,107,349 | OpenGL white window while code runs glew/glfw3 | So I am trying to draw two triangles, but at the end I just get the white window without any triangles. I have set up the libraries correctly but I believe there could be a mistake somewhere in the code and since I am fairly new I cannot figure it out. The code complies with no errors or warnings, but the outcome is not what I have expected the window is white and there is no drawing shown in the window.
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <cstdlib>
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
int main(void)
{
GLFWwindow* window;
// initialize the library
if (!glfwInit())
{
return -1;
}
// Create a window and its context
window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "kk", NULL, NULL);
int screenWidth, screenHeight;
glfwGetFramebufferSize(window, &screenWidth, &screenHeight);
if (!window)
{
glfwTerminate();
return -1;
}
// make the window's context current
glfwMakeContextCurrent(window);
glViewport(0, 0, screenWidth, screenHeight); //specifies part of the window OpenGL can draw on
glMatrixMode(GL_PROJECTION); //controls the camera
glLoadIdentity(); //put us at (0, 0, 0)
glOrtho(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT, 0, 600); //cordinate system
glMatrixMode(GL_MODELVIEW); //defines how objects are trasformed
glLoadIdentity(); //put us at (0, 0, 0)
GLfloat first_triangle[] = {
0, 0, 0,
0,300,0,
200,300,0,
};
GLfloat second_triangle[] = {
200,300,0,
400,300,0,
400,600,0,
};
GLfloat color[] =
{
255,0,0,
0,255,0,
0,0,255
};
// Loop until the window is closed by the user
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
//OpenGL rendering
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, first_triangle); // points to the vertices to be used
glColorPointer(3, GL_FLOAT, 0, color); // color to be used
glDrawArrays(GL_TRIANGLES, 0, 3); // draw the vetices
glVertexPointer(3, GL_FLOAT, 0, second_triangle); // points to the vertices to be used
glColorPointer(3, GL_FLOAT, 0, color); // color to be used
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
};
}
| You have to call glfwSwapBuffers and glfwPollEvents at the end of the application loop:
while (!glfwWindowShouldClose(window))
{
// [...]
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwSwapBuffers swaps the front and back buffers and causes the window to be updated.
glfwPollEvents process the events.
|
69,107,295 | 69,107,537 | How can I show a window with the a name given as parameter in Windows in C++ | I would like to make my software usable for Linux and Windows (Linux already works). Now I still need some functions so I can run the software on Windows, too.
I am currently trying to use the EnumWindows() function to get the window names and then show the window in the foreground (which matches the parameter).
static BOOL CALLBACK setWindowFocus(HWND hWnd, LPARAM lparam) {
int length = GetWindowTextLength(hWnd);
char* buffer = new char[length + 1];
GetWindowText(hWnd, buffer, length + 1);
std::string windowTitle(buffer);
// List visible windows with a non-empty title
if (IsWindowVisible(hWnd) && length != 0) {
// Check if it is the right Windowshandle
if ( windowTitle.compare(programname) == 0 ) <-- programname is a static variable
{
// Set application to the foreground
SetForegroundWindow(hWnd);
}
}
return TRUE;
}
Additionally, I used this to create the variable:
std::string programname;
And this to call it:
static void setWindowFocus(std::string programname)
{
std::cout << "Setting focus to window." << std::endl;
tempsavedProgramname=programname;
EnumWindows(setWindowFocus, NULL);
}
That is working, as long as it is in main(). But, I would like to have it in an extra class with some other functions (I would like to remove the static variable too, if possible).
Is there a way I can use the EnumWindows() function with an anonymous function, or something?
Can I use something like this to pass a string to the function:
EnumWindows(setWindowFocus, reinterpret_cast<LPARAM>(stringvariable));
Or, are there other ways which I can try to reach my goal?
Includes which I used for the code:
Windows.h
winuser.h
string
iostream
I hope that I did not forgot one.
| Yes, you can use the LPARAM to pass a string variable into your callback, eg:
static BOOL CALLBACK setWindowFocus(HWND hWnd, LPARAM lparam) {
std::string &programname = *reinterpret_cast<std::string*>(lparam);
int length = GetWindowTextLength(hWnd);
char* buffer = new char[length + 1];
GetWindowText(hWnd, buffer, length + 1);
std::string windowTitle(buffer);
delete[] buffer; // <-- ADD THIS!
/* I would use this instead:
int length = GetWindowTextLength(hWnd);
std::string windowTitle(length+1, '\0');
windowTitle.resize(GetWindowText(hWnd, &windowTitle[0], length + 1));
*/
// List visible windows with a non-empty title
if (IsWindowVisible(hWnd) && (length != 0)) {
// Check if it is the right Windowshandle
if (windowTitle == programname)
{
// Set application to the foreground
SetForegroundWindow(hWnd);
return FALSE;
}
}
return TRUE;
}
static void setWindowFocus(std::string programname)
{
std::cout << "Setting focus to window." << std::endl;
EnumWindows(setWindowFocus, reinterpret_cast<LPARAM>(&programname));
}
And yes, you can use a C++11 lambda for the callback, rather than a static class method, but only if you use a non-capturing lambda, which is implicitly convertible to a function pointer (capturing lambdas are not). Fortunately, the LPARAM makes that a possibility, eg:
static void setWindowFocus(std::string programname)
{
std::cout << "Setting focus to window." << std::endl;
EnumWindows(
[](HWND hWnd, LPARAM lparam) -> BOOL {
std::string &programname = *reinterpret_cast<std::string*>(lparam);
// ...
},
reinterpret_cast<LPARAM>(&programname)
);
}
Now, that being said, there is a much simpler solution - since you already know the exact window text you are looking for, you can use FindWindow() instead of EnumWindows(), eg:
static void setWindowFocus(std::string programname)
{
std::cout << "Setting focus to window." << std::endl;
HWND hWnd = FindWindowA(NULL, programname.c_str());
if (hWnd != NULL) {
// Set application to the foreground
SetForegroundWindow(hWnd);
}
}
|
69,107,418 | 69,107,856 | An ugly function finding the maximum std::set element less than a given key | When I write a code that is a bit strange I have a feeling that I probably misunderstand something.
Is there a better implementation of find_less function than provided below?
#include <iostream>
#include <set>
using Set = std::set<int>;
Set set{ 0, 1, 3, 7, 9, 10 };
Set::iterator find_less(int val)
{
auto i = set.lower_bound(val);
if (i == set.begin())
{
return set.end();
}
return --i;
}
int main()
{
auto i = find_less(5);
if (i != set.end())
{
//outputs 3
std::cout << *find_less(5) << std::endl;
}
return 0;
}
Isn't it a bit strange that std::set has lower_bound and upper_bound functions that find the first element that is greater than (or equal to) a given key, but it does not have functions that find an element that is less (or equal to) a given key?
EDIT1:
There is
std::lower_bound(set.rbegin(), set.rend(), val)
But looks like it is logarithmic only with random access iterators, see https://en.cppreference.com/w/cpp/algorithm/lower_bound : std::set and std::multiset iterators are not random access, and so their member functions std::set::lower_bound (resp. std::multiset::lower_bound) should be preferred.
| A simple solution that accounts for all potential inputs may be one that returns end() to exclusively mean
No element in the set meets the criteria
auto find_less(const Set& set, int val)
{
auto i = set.lower_bound(val);
return (i == set.begin()) ? set.end() : std::prev(i);
}
I have also changed your function signature to allow a set to be provided, instead of always searching one particular global variable.
|
69,107,694 | 69,123,095 | Why a Widget class uses pointers as data members? | I'm working through "Programming Principles and Practice", and I don't understand why this Widget class uses pointers as data members.
The book's explanations is this:
Note that our Widget keeps track of its FLTK widget and the Window with which it is associated. Note that we need pointers for that because a Widget can be associated with different Windows during its life. A reference or a named object wouldn’t suffice. (Why not?)
So, I still don't understand why the Widget can't have a named object Window win as a data member, which can take a different value when it's associated with a different Window. Could someone explain this a bit?
class Widget {
// Widget is a handle to a Fl_widget — it is *not* a Fl_widget
// we try to keep our interface classes at arm’s length from FLTK
public:
Widget(Point xy, int w, int h, const string& s, Callback cb)
:loc(xy), width(w), height(h), label(s), do_it(cb) { }
virtual ~Widget() { } // destructor
virtual void move(int dx,int dy)
{ hide(); pw–>position(loc.x+=dx, loc.y+=dy); show(); }
virtual void hide() { pw–>hide(); }
virtual void show() { pw–>show(); }
virtual void attach(Window&) = 0; // each Widget defines at least one action for a window
Point loc;
int width;
int height;
string label;
Callback do_it;
protected:
Window* own; // every Widget belongs to a Window
Fl_Widget* pw; // a Widget “knows” its Fl_Widget
};
| First, we need to work out the logical and implementation details. On the logical side, a window contains widgets: just like a mother has children. This is a one to many relationship. Each widget has an implementation entity, in this case an Fl_widget. It could equally be a MS windows Window, a QtWidget or and X-Windows Widget. It is one of those implementation dependent things
___________
|window |
| _______ | _________
| |widget-|-|--->|Fl_widget|
| _______ | _________
| |widget-|-|--->|Fl_widget|
|___________|
Within window itself, there will also be an implementation detail like another Fl_Widget or Fl_window.
The reason why we cannot have Window win instead of Window win* is because the window owns the widget and not the other way round. If we had Window win then whenever any window property changed, you'd have to modify all the widgets containing the same window. Taking, the mother child relationship, if the mother had a haircut, the mother member for all the children of the same mother would have to have a haircut. You'd have to have a method to keep track of and update all the mothers of all the children. This would just be a maintenance nightmare.
If we just hold a pointer to the window then we know that if the window is modified, all sibling widgets will be able to query the change in the parent window and get the same answer without a lot of effort.
The second part of your question about moving widgets between windows - I've never seen anyone do that. In all the implementations I have ever used, this is impossible. The parent window owns the widget for life. To "move it", you'd normally have to reincarnate it i.e. destroy it from the current window and re-create it in the new window.
|
69,108,136 | 69,108,184 | What does "type name[size]" mean in a function argument? | I was analyzing the SKIA source code and found this:
constexpr unsigned kMaxBytesInUTF8Sequence = 4;
// ...
SK_SPI size_t ToUTF8(SkUnichar uni, char utf8[kMaxBytesInUTF8Sequence] = nullptr);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
I know (pardon me if I'm wrong) that char utf8[kMaxBytesInUTF8Sequence] decays to char*, as also would char utf8[] or just char* utf8.
Therefore, I think it wouldn't make sense to write it that way, right?
| A function parameter having an array type is adjusted by the compiler to pointer to the array element type.
Thus these function declarations
SK_SPI size_t ToUTF8(SkUnichar uni, char utf8[kMaxBytesInUTF8Sequence] = nullptr);
SK_SPI size_t ToUTF8(SkUnichar uni, char utf8[10] = nullptr);
SK_SPI size_t ToUTF8(SkUnichar uni, char *utf8 = nullptr);
declare the same one function.
This parameter declaration
char utf8[kMaxBytesInUTF8Sequence]
is used for self-docimentation specifying that the passed array must have no greater than kMaxBytesInUTF8Sequence elements or the user can pass a null pointer.
|
69,108,401 | 69,108,667 | Is there a difference between a copy constructor with an argument type of `const T &` and of type `const T<U> &`? | As of C++11, std::allocator defines three constructors that are roughly equivalent to those in the following class:
template<typename T>
class allocator {
public:
constexpr allocator() noexcept = default;
constexpr allocator(const allocator &other) noexcept = default;
template<typename U>
constexpr allocator(const allocator<U> &other) noexcept {};
};
The first is a default constructor, and the second is a copy constructor - pretty standard stuff. However, the third constructor confuses me quite a bit. It appears to technically be a specialization of the copy constructor? And if that is the case, would the second constructor ever even be called? Is = default required? How does the compiler know to provide a default implementation for the third constructor?
|
It [the third constructor] appears to technically be a specialization of the copy constructor?
It is not a copy constructor at all. It is actually a converting constructor instead.
would the second constructor ever even be called?
If an allocator<T> object is used to construct another allocator<T> object, then the second constructor will be used, yes. For example:
allocator<int> a1;
allocator<int> a2(a1);
But, if a different allocator<U> object is used to construct an allocator<T> object, where U is not the same type as T, then the third constructor will be used. For example:
allocator<short> a1;
allocator<int> a2(a1);
Is = default required?
Only if you want the compiler to auto-generate an implementation. Otherwise, you have to provide one yourself.
How does the compiler know to provide a default implementation for the third constructor?
Everything between {} in a constructor's body is user-defined. If there is no {} then you need to use = default (or = delete) instead.
In a non-deleted constructor, the compiler always default-initializes each class member, unless specified otherwise in the constructor's member initialization list - which the 3rd constructor does not have.
|
69,108,418 | 69,108,525 | Temporary materialization on std::initializer_list<T> | I am reading about Temporarily Materialization, and got stuck on this point:
Temporary materialization occurs:
when initializing an object of type std::initializer_list<T> from a braced-init-list;
Does this mean that in this case:
std::initializer_list<int> x = std::initializer_list<int>{1,3,5};
the initializer_list is an actual prvalue that is going to be materialized?
If that's the case, does this mean that there's no copy elision going on here, even though after C++17 it should apply?
| Strictly speaking, it really doesn't matter, because there's no way you could ever observe whether a temporary std::initializer_list object is created.
But I think the answer is that the "materialization" described is the materialization of a temporary object with type int[3] (array of 3 ints) as described in [dcl.init.list]/5, to which the initializer_list object x is bound; it is not the materialization of a temporary initializer_list object. Copy elision is mandatory in this example.
|
69,108,629 | 69,109,212 | Compiling multiple c++ files doesn't work with certain file names | I am trying to compile multiple .cpp files, using a Makefile with make. I have a .cpp file containing the main function, in the other .cpp file a basic class (for every doubt I'll put all the code i'm using down here).
Example of names used to make it compile or to make it not compile:
-it works by having them named "prova.cpp"(contains the main function) and "pa.cpp"(contains the class) (below the commands done by the Makefile)
gioele@GioPC-U:~/Dev/Cpp/Exercises/666prova$ make
g++ -g -Wall -c src/prova.cpp -o obj/prova.o
g++ -g -Wall -c src/pa.cpp -o obj/pa.o
g++ -g -Wall obj/prova.o -o bin/provaBin
-it doesn't work by having them named "ciao.cpp"(contains the main function) and "pa.cpp"(contains the class)
gioele@GioPC-U:~/Dev/Cpp/Exercises/666prova$ make
g++ -g -Wall -c src/pa.cpp -o obj/pa.o
g++ -g -Wall -c src/ciao.cpp -o obj/ciao.o
g++ -g -Wall obj/pa.o -o bin/provaBin
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
(.text+0x24): undefined reference to `main'
collect2: error: ld returned 1 exit status
make: *** [Makefile:15: bin/provaBin] Errore 1
I think the problem is with the order of the files inside the Makefile. When it doesn't work is because is trying to get a binary from the .o without the main function. No idea on how to resolve.
The file with the main method:
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}
The class file:
class Class {
public:
int x;
int y;
};
The Makefile (still learning to work with Makefiles, probably the problem is here, any advice to make a Makefile of this kind better is appreciated, or if I am using something not properly):
CC=g++
CFLAGS=-g -Wall
OBJ=obj
SRC=src
BINDIR=bin
BIN=$(BINDIR)/provaBin
SRCS=$(wildcard $(SRC)/*.cpp)
OBJS=$(patsubst $(SRC)/%.cpp, $(OBJ)/%.o, $(SRCS))
all: $(BIN)
$(BIN): $(OBJS)
$(CC) $(CFLAGS) $< -o $@
$(OBJ)/%.o: $(SRC)/%.cpp
$(CC) $(CFLAGS) -c $< -o $@
clean:
$(RM) $(BINDIR)/* $(OBJ)/*
Thank you in advance.
| You can fix this by changing one character.
In this rule:
$(BIN): $(OBJS)
$(CC) $(CFLAGS) $< -o $@
the prerequisite list $(OBJS) expands to a list of object files, such as prova.o pa.o or pa.o ciao.o. You want Make to incorporate that list into the linking command, like this:
g++ -g -Wall prova.o pa.o -o bin/provaBin
But the automatic variable $< expands to only the first item in the prerequisite list. If the first item is an object file that does not contain the main() function, such as pa.o, the linker will complain that main() is missing. (If it is an object file that contains main(), such as prova.o, then you will not get that error, but you may still have problems.)
The solution is to use the automatic variable $^, which expands to the complete list of prerequisites:
$(BIN): $(OBJS)
$(CC) $(CFLAGS) $^ -o $@
|
69,108,786 | 69,110,125 | Move object within its own destructor | If I have a move-only class which is initially owned by AManager, can be transferred to another owner via obtain, returned back to AManager via release.
class AManager;
class A {
public:
A(const A& other) = delete;
const A& operator=(const A&) = delete;
A(A&& other);
A& operator=(A&& other);
private:
AManager& _manager;
bool _isValid;
};
class AManager {
public:
A obtain() {
return std::move(_instance);
}
void release(A a) {
_instance = std::move(a);
}
private:
A _instance;
};
Is it valid for A to move itself within its own destructor? i.e., is it valid for A to release itself back to its manager when it is destroyed?
A::~A() {
if (_isValid) {
_manager.release(std::move(*this));
}
}
Assuming the A class has some way to know if its in a valid state. For example, I added a valid flag. I believe unique_ptr uses the pointer being null or not.
|
is it valid for A to release itself back to its manager when it is destroyed?
"Valid" in what sense? Will it compile? Yes.
Does it make any kind of sense? No.
You are moving an object that is being destroyed. The owner of that object requested and expects the resources managed by this object to no longer exist. By giving those resources back to the manager, they will continue to exist.
Basically, what you have is pretend-shared-ownership. The manager can pretend to share ownership with you, but in reality, it always owned the object and true ownership of those resources can never be relinquished. It's like a shared_ptr, except that its use count can never exceed 2.
Also, there are no apparent safeguards in place should A outlive its manager, unlike with a proper shared pointer. The reference will simply reference a destroyed object, leading to UB when the A instance is destroyed.
If you want to share ownership, then share it. If you don't, then don't. But this half-state makes your code brittle.
|
69,109,280 | 69,109,591 | C++ re-assignable const member variable | In C++, suppose I have a member variable of type Bar, and I want to make sure only const methods are called on it. So then AFAIK I can declare it as a const Bar member variable like below:
class Foo
{
public:
Foo(const Bar& b) : bar(b) {}
void setBar(Bar& b) {
bar = b; // compiler complains here
}
private:
const Bar bar;
}
But I also want to be able to re-assign bar altogether. Is this possible to do without the compiler complaining?
| The "trick" is to have your member data be a std::shared_ptr<const Bar> instead of const Bar; you can then re-assign the shared_ptr at will, but can't change Bar since the pointer is const.
#include <memory>
struct Bar final {};
struct Foo final
{
//Foo(const Bar& b) : bar(b) {}
Foo(const Bar& b) : pBar(std::make_shared<const Bar>(b)) {}
void setBar(const Bar& b) {
//bar = b; // compiler complains here
pBar = std::make_shared<const Bar>(b);
}
private:
//const Bar bar;
std::shared_ptr<const Bar> pBar;
};
Note that std::unique_ptr might be better than std::shared_ptr, but then you've got to add copy/assignment, assuming you want those. However, since it's a shared_ptr to constBar, it's not all that bad.
|
69,109,374 | 69,109,404 | error: ‘_cal_order’ was not declared in this scope - scoping issue | I am starting to learning C++ and am trying some simple examples. However the example below gives me the following error:
main.cpp:20:32: error: ‘_cal_order’ was not declared in this scope
double pos=_cal_order(p,n,l);
I am just trying to pass 3 variables to a function and return a double result. Here is the code:
#include<math.h>
#include <iostream>
using namespace std;
int main()
{
int n = 5000;
double p = 45000.0;
double l = 0.001;
double pos=_cal_order(p,n,l);
cout<<pos<<endl;
};
double _cal_order(double p, int n, double l)
{
return static_cast<double>(round(n/(p*l)))*l;
};
| You must declare the function before using it.
Option 1: Define it first
#include<math.h>
#include <iostream>
using namespace std;
double _cal_order(double p, int n, double l)
{
return static_cast<double>(round(n/(p*l)))*l;
};
int main()
{
int n = 5000;
double p = 45000.0;
double l = 0.001;
double pos=_cal_order(p,n,l);
cout<<pos<<endl;
};
Option 2: Declare it first, define it later
#include<math.h>
#include <iostream>
using namespace std;
double _cal_order(double p, int n, double l);
int main()
{
int n = 5000;
double p = 45000.0;
double l = 0.001;
double pos=_cal_order(p,n,l);
cout<<pos<<endl;
};
double _cal_order(double p, int n, double l)
{
return static_cast<double>(round(n/(p*l)))*l;
};
|
69,109,472 | 69,110,634 | How to add a key with a dot in the name to a json file | I am reading some information and I want to write it in json, but the names of some keys contain dots in the name. I want to get something like this:
{
"programs":
{
"tmp.exe" : "D:\\Directory\\Directory",
"foo.exe" : "C:\\Directory"
}
}
This is my code:
ptree pt;
ptree name;
name.put(string_name,string_directory);
pt.add_child("programs",name);
But it turns out the following:
{
"programs":
{
"tmp":
{
"exe" : "D:\\Directory\\Directory"
},
"foo":
{
"exe" : "C:\\Directory"
}
}
}
I was thinking about adding it as a child. But this code does not work at all
ptree pt;
ptree name;
name.put("",string_name);
pt.add_child("programs",name);
pt.find(string_name).put_value(string_directory);
| Although all JSON linters I've tested accepts your target JSON as valid and boost::property_tree::read_json parses it, actually creating it is a bit cumbersome. This is because boost::property_tree uses . as a path separator by default.
To overcome this, you can specify the Key with a different ptree::path_type than the default in which you specify another character. I've used \ as a path separator here because that's unlikely going to be a part of the basenames of your files.
Example:
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <iostream>
int main() {
using namespace boost::property_tree;
try {
ptree pt;
ptree name;
name.put(ptree::path_type{"tmp.exe", '\\'}, "D:\\Directory\\Directory");
name.put(ptree::path_type{"foo.exe", '\\'}, "C:\\Directory");
pt.add_child("programs", name);
write_json(std::cout, pt);
} catch(const std::exception& ex) {
std::cout << "exception: " << ex.what() << '\n';
}
}
Output:
{
"programs": {
"tmp.exe": "D:\\Directory\\Directory",
"foo.exe": "C:\\Directory"
}
}
|
69,109,774 | 69,109,902 | What is the best way to return multiple large objects in C++? | I want to return a tuple containing types like std::vector or std::unordered_map etc. where the objects may be large enough that I care about not copying. I wasn't sure how copy elision / return value optimization will work when the returned objects are wrapped in a tuple. To this end I wrote some test code below and am confused by parts of its output:
#include <tuple>
#include <iostream>
struct A {
A() {}
A(const A& a) {
std::cout << "copy constructor\n";
}
A(A&& a) noexcept {
std::cout << "move constructor\n";
}
~A() {
std::cout << "destructor\n";
}
};
struct B {
};
std::tuple<A, B> foo() {
A a;
B b;
return { a, b };
}
std::tuple<A, B> bar() {
A a;
B b;
return { std::move(a), std::move(b) };
}
std::tuple<A, B> quux() {
A a;
B b;
return std::move(std::tuple<A, B>{ std::move(a), std::move(b) });
}
std::tuple<A, B> mumble() {
A a;
B b;
return std::move(std::tuple<A, B>{ a, b });
}
int main()
{
std::cout << "calling foo...\n\n";
auto [a1, b1] = foo();
std::cout << "\n";
std::cout << "calling bar...\n\n";
auto [a2, b2] = bar();
std::cout << "\n";
std::cout << "calling quux...\n\n";
auto [a3, b3] = quux();
std::cout << "\n";
std::cout << "calling mumble...\n\n";
auto [a4, b4] = mumble();
std::cout << "\n";
std::cout << "cleaning up main()\n";
return 0;
}
when I run the above (on VS2019) I get the following output:
calling foo...
copy constructor
destructor
calling bar...
move constructor
destructor
calling quux...
move constructor
move constructor
destructor
destructor
calling mumble...
copy constructor
move constructor
destructor
destructor
cleaning up main()
destructor
destructor
destructor
destructor
So from the above is looks like bar() is best which is return { std::move(a), std::move(b) }. My main question is why foo() ends up copying? RVO should elide the tuple from being copied but shouldn't the compiler be smart enough to not copy the A struct? The tuple constructor could be a move constructor there since it is firing in an expression that is being returned from a function i.e. because struct a is about to not exist.
I also don't really understand what is going on with quux(). I didnt think that additional std::move() call was necessary but I don't understand why it ends up causing an additional move to actually occur i.e. I'd expect it to have the same output as bar().
|
My main question is why foo() ends up copying? RVO should elide the
tuple from being copied but shouldn't the compiler be smart enough to
not copy the A struct? The tuple constructor could be a move
constructor
No, move constructor could only construct it from another tuple<> object. {a,b} is constructing from the component types, so the A and B objects are copied.
what it going on with quux(). I didnt think that additional
std::move() call was necessary but I don't understand why it ends up
causing an additional move to actually occur i.e. I'd expect it to
have the same output as bar().
The 2nd move happens when you are moving the tuple. Moving it prevents the copy elision that occurs in bar(). It is well-know that std::move() around the entire return expression is harmful.
|
69,110,253 | 69,110,701 | How can I read and write text files using the windows api | There are many similar questions, but mine is a bit different. Mine involves a Windows GUI. I am using an open file dialog or an "OPENFILENAME". I want to get the dialog result as OK when the user clicks the OK button and then open a text encoded file. I have done it in Java, but the UI looks weird. So I am not sure whether or not people would like it. I want to learn C++ as well, so I need some help. I have a text box called "hWndEdit" in the WM_COMMAND message inside my program. After opening, the text in the file is supposed to be displayed in the textBox I have specified. I have defined the function in a header file with the following code:
#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;
void OpenFile()
{
OPENFILENAME ofn; // common dialog box structure
HWND hwnd = nullptr; // owner window
HANDLE hf; // file handle
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = L"NoteRecorder Notes\0(*.recnote)\0Text\0(*.txt)\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
// Display the Open dialog box.
if (GetOpenFileName(&ofn) == TRUE)
{
hf = CreateFile(ofn.lpstrFile,
GENERIC_READ,
0,
(LPSECURITY_ATTRIBUTES)NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
(HANDLE)NULL);
}
}
Then I call it from my WM_COMMAND message:
case WM_COMMAND:
switch (wParam)
{
case 12:
OpenFile();
break;
}
But when the user presses the OK button in the OPENFILENAME, it doesn't read any text from the file. How can I accomplish this?
And I want to write files with a save file dialog. Tell me how to do that as well.
| The main purpose of the functions GetOpenFileName and GetSaveFileName is to provide you with the filename that the user selected. However, doing the actual File Input and Output is a different issue. You can use the standard C/C++ library for that or you can use the Windows API functions, such as CreateFile, ReadFile and WriteFile.
Since you seem to already be using the function CreateFile, it would make sense to call ReadFile after verifying that the function call to CreateFile succeeded (i.e. that it did not return INVALID_HANDLE_VALUE). After reading the data, you can add a terminating null character to the data (you should make sure that the memory buffer is large enough) and then pass it to the SetDlgItemText function (if the text box is in a dialog box) or SetWindowText function.
|
69,110,367 | 69,122,925 | WinUI 3 Desktop XAML Databinding - WinRT originate error - 0x8001010E when the Property is changed | I am following the BookStore data binding example, documented at XAML controls; bind to a C++/WinRT property, up to and including the "Bind the button to the Title property" section.
My starting point is a new "Blank App, Packaged (WinUI 3 in Desktop)" project in Visual Studio.
[EDIT] Starting from a "Blank App (C++/WinRT)" project, which is for UWP apps, works perfectly. The problem persists with "WinUI 3 in Desktop" projects.
The initial data binding works and the button content L"Atticus" is read from the BookSku title property. However calling MainViewModel().BookSku().Title(L"To Kill a Mockingbird"); in the click handler, as directed in article, throws the exception
Exception thrown at 0x00007FFC801B4ED9 (KernelBase.dll) in BookStore.exe: WinRT originate error - 0x8001010E : 'The application called an interface that was marshalled for a different thread.'.
Stepping through the code, the call
m_propertyChanged(*this, Windows::UI::Xaml::Data::PropertyChangedEventArgs{ L"Title" });
in void BookSku::Title(hstring const& value) is where the exception is thrown from within.
I can change the button content manually, not through the binding property.
The first example in the Data binding in depth article describes a very similar, though slightly less complicated, data binding scenario. It throws the same exception.
I am using latest Microsoft.Windows.CppWinRT version 2.0.210825.3 and Windows App SDK version 0.8.3
| This issue #4547 was the key to figuring out the solution. You need to use the Microsoft namespace, not Windows. For documentation purposes this is what the BookSku.idl file should look like:
// BookSku.idl
namespace Bookstore
{
runtimeclass BookSku : Microsoft.UI.Xaml.Data.INotifyPropertyChanged
{
BookSku(String title);
String Title;
}
}
|
69,110,661 | 69,110,699 | Inheritance mess with pure virtual functions, any way to not have to re-define them all? | So I found myself in a bit of a mess of a class hierarchy.
I have code that looks a bit like that, oversimplified:
#include <iostream>
struct Parent {
virtual void pureVirtual() = 0;
};
struct Child : public Parent {
void pureVirtual() override {
std::cout << "Child::pureVirtual()" << std::endl;
}
};
struct Brother: public Parent {
};
struct GrandChild : public Child, public Brother {
};
GrandChild test;
The compilation fails with:
object of abstract class type "GrandChild" is not allowed: -- pure virtual function
"Parent::pureVirtual" has no overriderC/C++(322)
I don't fully understand why the implementation of pureVirtual is not inherited by GrandChild from Child.
In practice, I have tons of pure-virtual functions to "re-implement", that is, just writing lines like:
struct GrandChild : public Child, public Brother {
void pureVirtual() override {
Child::pureVirtual();
}
};
I would have expected the compilator to automatically use the implementation from Child.
Is there any sort of trick I can use to tell the compiler that I am gonna re-use all the implementations from Child?
Anyway I probably have to think of a better design, but this got me interested if there are easy solutions.
| The issue is that you actually are getting two pureVirtual functions. C++ isn't smart enough to merge the two by default. You can use virtual inheritance to force the behavior.
#include <iostream>
struct Parent {
virtual void pureVirtual() = 0;
};
struct Child : virtual public Parent {
void pureVirtual() override {
std::cout << "Child::pureVirtual()" << std::endl;
}
};
struct Brother : virtual public Parent {};
struct GrandChild : public Child, public Brother {};
int main() {
GrandChild test;
}
|
69,110,725 | 69,110,946 | Write a program that reads a string of characters and calls a recursive function to determine if the letters in the string form a palindrome | I'm tasked with a project to write a recursive function that will determine if a user inputted string is a palindrome or not. I think I have a very strong foundation of code for the problem, but it doesn't seem to work how I want it to.
I was doing some troubleshooting to figure out what was wrong and it appears that if my string is <= 8 characters long the length of the array automatically becomes 14 for some reason. Could use some troubleshooting and input from people better at c++ than myself.
Here is my code:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
bool isPalindrome(char[], int, int);
int main()
{
char palin[100],
lowerPalin[100];
cout << "Enter a line that might be a palindrome:" << endl;
cin.get(palin, 100);
for (int i = 0, x = 0; i < strlen(palin); i++) // this for loop will remove punctuation, white space and make it all lowercase
{
if((palin[i] != ' ') && (ispunct(palin[i]) == false))
{
lowerPalin[x] = tolower(palin[i]); // transfering inputted array into new array with just alpha characters
x++;
}
}
int low = 0,
high = strlen(lowerPalin);
if (isPalindrome(lowerPalin, low, high))
cout << "The string is a palindrome." << endl;
else
cout << "The string is NOT a palindrome." << endl;
return 0;
}
bool isPalindrome(char lowerPalin[], int low, int high)
{
if (lowerPalin[low] == lowerPalin[high])
return isPalindrome(lowerPalin, low + 1, high - 1);
if (lowerPalin[low] != lowerPalin[high])
return false;
return true;
}
I'm still trying to learn recursion as well, so if anything is wrong with my bottom function please let me know.
EDIT: Thank you all for the help! I was able to understand and fix my mistake thanks to you all. Also thanks for all the tips in your answers, it helps a new student, like myself, a lot!
| Assumption : you're being forced to use recursion, character arrays, and not allowed to use the functions in <algorithm> that pretty much do all the work for you.
The bug: lowerPalin was not null terminated. That makes high = strlen(lowerPalin); a fatal mistake. strlen counts characters untill it finds a null, so without a null, Crom only knows what strlen will return. If it ever does.
Solution
int x = 0; // need to keep x live after the loop in order to ensure null-termination
for (int i = 0; i < strlen(palin); i++) // this for loop will remove punctuation, white space and make it all lowercase
{
if ((palin[i] != ' ') && (ispunct((unsigned char)palin[i]) == false))
{
lowerPalin[x] = tolower((unsigned char)palin[i]);
x++;
}
}
lowerPalin[x] = '\0'; // null terminate the string or it's not a string.
// It's just a bunch of characters and `strlen` can't
// be trusted.
That said, as soon as x outlives the loop, you don't need strlen. high = x; and done. Sort of. See below for why it's not really this easy.
Modified code with corrections and general commentary embedded as comments
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
bool isPalindrome(char[], int, int);
int main()
{
char palin[100], lowerPalin[100];
cout << "Enter a line that might be a palindrome:" << endl;
if (!cin.get(palin, 100)) // always test the stream state for success
{
cout << "bad input, dude." << endl;
return -1;
}
int x = 0; // need to keep x alive after the loop in order to get length of string
// a different way to iterate the string that doesn't rely on strlen
for (char * chp = palin; // get pointer to first character in array
*chp != '\0'; // loop until we find the null terminator
++chp) // advance pointer to next character
{
if ((*chp != ' ') && (ispunct((unsigned char)*chp) == false))
{
lowerPalin[x] = tolower((unsigned char)*chp);
// This one is weird. tolower's parameter is an int, not a char, and
// you can have unfortunate results if sign extension takes place.
// always make sure you use unsigned char with ispunct and any of
// the other ctype functions.
x++;
}
}
int low = 0, high = x-1; // We know the size of the string thanks to x
// but we don't really want the length of the
// string. we want the position of the last
// character in the string.
if (isPalindrome(lowerPalin, low, high))
{
cout << "The string is a palindrome." << endl;
}
else
{
cout << "The string is NOT a palindrome." << endl;
}
return 0;
}
bool isPalindrome(char lowerPalin[], int low, int high)
{
if (low >= high) // when high and low meet or pass, we're done looking.
{ // everything has been compared
return true; // if we got here, it's a palindrome.
}
if (lowerPalin[low] == lowerPalin[high])
{ // Found a match. Keep looking
return isPalindrome(lowerPalin, low + 1, high - 1);
}
return false; // no match. stop looking
}
|
69,111,070 | 69,111,086 | Why the C++ linker doesn't complain about missing definitions of theses functions? | I have written this code:
// print.h
#pragma once
#ifdef __cplusplus
#include <string>
void print(double);
void print(std::string const&);
extern "C"
#endif
void print();
And the source file:
// print.cxx
#include "print.h"
#include <iostream>
void print(double x){
std::cout << x << '\n';
}
void print(std::string const& str){
std::cout << str << '\n';
}
void print(){
printf("Hi there from C function!");
}
And the driver program:
// main.cxx
#include "print.h"
#include <iostream>
int main(){
print(5);
print("Hi there!");
print();
std::cout << '\n';
}
When I compile:
gcc -c print.cxx && g++ print.o main.cxx -o prog
The program works just fine but what matter me a lot is:
I compiled print.cxx using gcc which doesn't define the C++ version print(double) and print(std::string). So I get print.o that contains only the definition of the C version of print().
When I used G++ to compile and build the program I passed print.o to it along with the source file main.cxx. It produces the executable and works fine but inside main.cxx I called the C++ versions of print (print(double) and print(std::string)) and these ones are not defined in prnint.o because it has been compiled using GCC and because of the macro __cplusplus (conditional compilation). So how come that the linker doesn't complain about missing definitions of those functions?? Thank you!
|
I compiled print.cxx using gcc which doesn't define the C++ version...
Not quite. gcc and g++ both invoke the same compiler suite. And the suite has a set of file extensions it automatically recognizes as either C or C++. Your *.cxx files were all compiled as C++, which is the default behavior for that extension.
You can use the -x option to override the default behavior.
|
69,111,146 | 69,111,482 | How to find the number of chars in a string | I am trying to write a program that will take two inputs: the first a char and the second a string. The program will then search through the string, one place at a time and keep track of how many times the char that the user input occurs in the string.
I cannot seem to find my mistake, but the for loop in my CountCharacters function seems to not be iterating. Can anyone offer any assistance?
#include <iostream>
#include <string>
using namespace std;
int CountCharacters(char userChar, string userString) {
int charCounter = 0;
int i;
for (i = 0; i > userString.length(); ++i) {
if (userString.at(i) == userChar) {
charCounter += 1;
}
}
return charCounter;
}
int main() {
char userChar;
string userString;
cin >> userChar;
getline(cin, userString);
cout << CountCharacters(userChar, userString);
return 0;
}
| As @user4581301 pointed out, the condition in your for-loop doesn't make sense. If you set the value of i = 0 and then check whether i > userString.length(), the boolean expression will always evaluate to false, since 0 will never be greater than the length of the inputted word. If your condition for your loop evaluates to false at the beginning itself, it will never start looping.
for (i = 0; i < userString.length(); ++i)
Here, i is still 0, but the boolean expression checks whether i < userString.length(). In the initial iteration, 0 will be less than the length of the inputted word, so the boolean expression will evaluate to true and the loop will run.
|
69,111,874 | 69,113,070 | 'Candidate template ignored: couldn't infer template argument' with std::set | I'm writing a function to manipulate a set with it's iterators, and it's giving me the error
candidate template ignored: couldn't infer template argument
The minimum reproducible code is as follows:
#include <bits/stdc++.h>
using namespace std;
template <typename T>
void foo(typename set<T>::iterator it1)
{
// do something
}
int main()
{
set<int> aSet;
foo(aSet.begin()); // no matching function call to 'foo'
}
I tried including <set> directly, changing the order of function definitions, but nothing solved it. And the weirdest thing is that I used the set iterator as parameter in other functions, and it worked.
These other function declarations were something like this:
template <typename T>
void bar(set<T>& aSet, vector<T>& aVector, typename set<T>::iterator it);
(these exact parameters, in this exact order).
| In foo the T in argument typename set<T>::iterator is a non-deduced contexts:
...the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.
The T is used in this non-deduced contexts and does not explicitly specify in foo what type it should deduce to, the compiler can not deuce the type; hence the error!
That means, if you explicitly mention what T in foo, it will compile as mentioned in the quote.
foo<int>(aSet.begin()); // compiles!
or better, provide the iterator as template parameter
template <typename Iterator>
void foo(Iterator it1)
If you want to restrict the Iterator only for std::set<T>::iterator, you can SFINAE function. Here is an example code.
#include <type_traits> // std::enable_if, std::is_same
#include <iterator> // std::iterator_traits
template<typename Iterator>
inline constexpr bool is_std_set_iterator =
std::is_same_v<Iterator, typename std::set<typename std::iterator_traits<Iterator>::value_type>::iterator> ||
std::is_same_v<Iterator, typename std::set<typename std::iterator_traits<Iterator>::value_type>::const_iterator>;
template <typename Iterator>
auto foo(Iterator it1) -> std::enable_if_t<is_std_set_iterator<Iterator>, void>
{
// do something
}
On the other hand, in bar the compiler already deduced the first function argument to std::set<int>& aSet and sees the typename std::set<T>::iterator, which it can deduce to typename std::set<int>::iterator, because T was already deduced to int in the previous function argument. Hence, it works!
As a side note, see the followings:
Why should I not #include <bits/stdc++.h>?
Why is "using namespace std;" considered bad practice?
|
69,111,975 | 69,112,050 | how can I not create precompiled header when compile object file? | I use g++ 10.2.0 and try to create a static library, but when I create object file for archiving a static library, object file format always shows precompiled header, it makes the final static library cannot work:
//file static_test.cpp
void fn(){
int temp;
++temp;
}
//file static_test.h
void fn();
build them but not link
g++ -c static_test.h static_test.cpp -o static_test.o
use file to show static_test.o format
file static_test.o
static_test.o:GCC precompiled header (version 014) for C++
and I archive it
ar rsv libstatic_test.a static_test.o
use file to show libstatic_test.a format:
current ar archive
use a main.cpp to test this static library
#include "static_test.h"
int main(){
fn();
return 0;
}
compile them and link
g++ main.cpp libstatic_test.a
libstatic_test.a: cannot add symbol: archive has no index;run ranlib to add one
collect2: error:ld return 1
why and how to solve this problem, tks~
| -c is only for a single file, the second static_test.cpp is ignored. You should get the compiler warning about multiple files set to -c. g++ -c static_test.h results the precompiled header in static_test.o and static_test.cpp is ignored. The proper command should be
g++ -c static_test.cpp -o static_test.o
Do not pass header files to the compiler when you compile object files. All other commands you are using look ok.
|
69,112,012 | 69,114,818 | how do I tell an array pointer from a regular pointer | I'm writing a smart pointer like std::shared_ptr since my compiler does not support c++17 and later versions, and I want to support array pointer like:
myptr<char []>(new char[10]);
well, it went actually well, until I got the same problem as old-version std::shared_ptr got:
myptr<char []>(new char);
yeah, it can't tell whether it's a regular pointer or an array pointer, and since my deleter is kind of like:
deleter = [](T *p) {delete[] p;}
which means it just meets the same problem that the old-version std::shared_ptr has.
my array-pointer partial specialization is like:
template <typename T, typename DeleterType>
class myptr<T[], DeleterType> { // DeleterType has a default param in main specialization
// as std::function<void(T*)>
private:
my_ptr_cnt<T, DeleterType> *p; // this is the actual pointer and count maintain class
public:
// constructor
/// \bug here:
my_ptr(T *p, DeleterType deleter=[](T *p) {delete []p;}) :
p(new my_ptr_cnt<T, DeleterType>(p, deleter)) { }
}
| You can't. This is one of the many reasons that raw arrays are bad.
What you can do is forbid construction from raw pointer, and rely on make_shared-like construction.
|
69,112,227 | 69,115,147 | Write a recursive function that will write the prime factors of a user inputted number | I have posted about recursion a few times and I now understand it, although this problem has been stuck with me for quite some time now. I am supposed to write a program with two functions:
1. a function that returns the lowest prime factor of a user inputted number
2. a recursive function that calls the first function and displays the other prime factors
I have figured out the first function, but I cant seem to understand how to write the second function, if you guys could provide solutions and your input that would be great! (I was also messing around in the second function, but I don't think it leads to anything important so ignore that code).
Here's my code:
#include <iostream>
using namespace std;
int smallFactor(int);
int isPrime(int);
int main()
{
int posInt;
cout << "Enter one positive integer: ";
cin >> posInt;
cout << "The prime factors of " << posInt << " are ";
int newInt;
newInt = isPrime(posInt); // this is me messing around trying to see how my program should work together
smallFactor(newInt); // this is me messing around trying to see how my program should work together
return 0;
}
int smallFactor(int posInt)
{
if (posInt % 2 == 0)
return 2;
for (int i = 3; i * i <= posInt; i += 2)
{
if (posInt % i == 0)
return i;
}
return posInt;
}
int isPrime(int posInt)
{
// honestly no clue what im doing in this function, was just messing around to get ideas
cout << smallFactor(posInt) << " ";
int newInt = posInt / smallFactor(posInt);
return newInt;
}
| the recursive function can be:
//posInt should greater than 1;
void OutputPrimeFactors(int posInt)
{
if(posInt == 1)
return;
int k = smallFactor(posInt);
cout << k;
if(k < posInt)
{
cout << ", ";
OutputPrimeFactors(posInt / k);
}
}
|
69,112,630 | 69,112,752 | How to convert a data of type LPTSTR to HWND? | How to convert a data of type LPTSTR to HWND?
i tried: example
LPTSTR hwnd = L"0x000511E8";
HWND window_hwnd = (HWND)hwnd;
But the value on window_hwnd is not the same as before, and I cant find the window by utilizing this value.
| I think you mean: How to convert a string to a HWND value?
That can be done like this:
#include <Windows.h>
#include <string>
int main()
{
const std::wstring hwnd_str{ L"0x000511E8" }; // to show std::wstring :)
auto value = std::stoull(hwnd_str, nullptr, 16); // convert from hex (base 16) to unsigned long long (needed for HWND conversion next line)
HWND window_hwnd = reinterpret_cast<HWND>(value);
}
|
69,113,758 | 69,113,832 | undefined reference to `Account::set_balance(double)' ----What does it mean? | Account.h file
#ifndef ACCOUNT_H
#define ACCOUNT_H
class Account
{
private:
//attributes
double balance;
public:
//methods
void set_balance(double bal);
double get_balance();
};
#endif
Account.cpp file
#include "Account.h"
void Account::set_balance(double bal){
balance=bal;
}
double Account::get_balance(){
return balance;
}
main.cpp file
#include<iostream>
#include"Account.h"
int main(){
Account frank_account;
frank_account.set_balance(200.00);
double showBalance=frank_account.get_balance();
return 0;
}
error
C:\Users\Dell\AppData\Local\Temp\ccZOi0ua.o: In function `main':
F:/OPP/opp10/main.cpp:6: undefined reference to `Account::set_balance(double)'
F:/OPP/opp10/main.cpp:7: undefined reference to `Account::get_balance()'
collect2.exe: error: ld returned 1 exit status
Build finished with error(s).
The terminal process terminated with exit code: -1.
Please explain the error message and provide the solution.
Thank You....................................................................................................................
| How did you compile these two files? This error suggests that the "Account.cpp" is not compiled or linked by you. Try this:
gcc Account.cpp main.cpp
|
69,113,785 | 69,113,855 | Is it possible to put my c++ code into a window rather than opening in command prompt? | My code is: Is it possible to put this in a window instead of opening up a command prompt as I feel that would be more user-friendly? And would just look better overall I have Searched online and haven’t found any way to put any code in a window.
#include <iostream>
using namespace std;
int main()
{
while (true) {
string s;
int n, i, m = 0, flag = 0;
cout << "(press 'x' to exit) Enter the Number to check if It's a prime Number or not: ";
cin >> s;
if (s == "x")
break;
n = atoi(s.c_str());
m = n / 2;
for (i = 2; i <= m; i++)
{
if (n % i == 0)
{
cout << "That's not a prime number." << endl;
flag = 1;
break;
}
}
if (flag == 0)
cout << "That's a prime number." << endl;
}
}
| You can follow the microsoft docs tutorial for creating a window.
You won't be able to use std::cout and std::cin as these are console specific.
|
69,113,980 | 69,115,103 | If two functions are in arithmetic operations in recursion, which function will work first? | int count(int S[], int m, int n)
{
if (n == 0)
return 1;
if (n < 0)
return 0;
if (m <= 0 && n >= 1)
return 0;
return count(S, m - 1, n) + count(S, m, n - S[m - 1]);
}
Does it end with count(S, m - 1, n) and then start with the next count(S, m, n - S[m - 1])? Or do two have to be calculators from both sides at the same time? Will there be any value change of count(S, m, n - S[m - 1]) for count(S, m - 1, n)?
Here is my full code
| See Order of evaluation
in
return count(S, m - 1, n) + count(S, m, n - S[m - 1]);
we just have the guaranty that:
S, m-1 (first one) and n are computed before count(S, m - 1, n)
m-1 (second one) is computed before S[m - 1]
S[m - 1] is computed before n - S[m - 1]
S, m, and n - S[m - 1] are computed before count(S, m, n - S[m - 1])
in particular
count(S, m - 1, n) can be computed before or after count(S, m, n - S[m - 1]) (and that for any call) (and they cannot "overlap", one is computed before the other).
Fortunately, count doesn't have side effects or change their arguments, so any order is correct in your cases.
|
69,114,044 | 69,116,951 | When do you need to explicitly call std::move and when not in cpp? | I'm working through Stroustrup's "Tour of C++ v2". It's certainly not a C++ beginner's book, but enjoyable.
I've had a google and look through SO but no joy on this one.
Now, I thought I understood when the compiler can utilise a move constructor, but clearly I don't. Here I show the move constructor and the function that I thought would use it. It doesn't. Only if I explicitly use std::move. Why is this? My understanding was that the local r would be "moved" implicitly on return.
template<typename T>
Vector<T>::Vector(Vector<T> && a) // move constructor
:elem{a.elem},sz{a.sz}{
a.elem=nullptr;
a.sz=0;
}
template<typename T>
Vector<T> moveVectorAfterAdd(const Vector<T> & v1, const Vector<T> & v2){
Vector<T> r = v1+v2;
return std::move(r);
//return r;
}
int main(void) {
Vector<double> v1(1);
Vector<double> v2=v1;
Vector<double> v3=v2;
Vector<double> v4=moveVectorAfterAdd(v1,v2);
return 0;
}
(As a side note, lldb won't let me even set a break point in the move constructor despite compiling with no optimizations if I don't actually use std::move.)
Any and all clarifications gladly received!
|
When do you need to explicitly call std::move and when not in cpp?
In short, and technically precise words: Use std::move when you have an lvalue that you want to be an rvalue. More practically: You would want to do that when there is a copy that you want instead to be a move. Hence the name std::move.
In the example, you return an automatic variable. There is no copy that can be avoided by using std::move because in the special case of returning an automatic variable, there will be a move even from an lvalue.
Here I show the move constructor and the function that I thought would use it. It doesn't.
Just because there is a move in the abstract machine, doesn't necessarily mean that there would be a call to the move constructor. This is a good thing because doing nothing can potentially be faster than calling the move constructor.
This is known as (Named) Return Value Optimization. Or more generally copy elision. Using std::move inhibits this optimization, so not only is it unnecessary in this case, but it is also counter productive.
|
69,114,268 | 69,122,679 | Why the address of entry point doesn't match NT header? | I want to find out the entry of a windows program. as far as MS documents describes "ImageBase":
When the linker creates an executable, it assumes that the file will
be memory-mapped to a specific location in memory. ...
I use dumpbin to show ImageBase in PE header, to find where to map:
>dumpbin /HEADERS my.exe
...
13D0 entry point (00000001400013D0) mainCRTStartup
1000 base of code
140000000 image base (0000000140000000 to 0000000140006FFF)
...
So that entry function mainCRTStartup is mapped to virtual address 0x00000001400013D0 , but when I run the program and print address:
with __ImageBase = 0x7ff771e60000
with mainCRTStartup = 0x7ff771e61390
that address printed by program seems to be at the bottom of user space (near windows dlls), far away from "image base + entry point". Why is that?
I also tried to examine memory at 0x00000001400013D0 , and there seems to be no mapped pages.
here is the source (build by vs2019, x64):
#include <Windows.h>
#include <stdio.h>
extern "C" const IMAGE_DOS_HEADER __ImageBase;
extern "C" int mainCRTStartup();
int main() {
printf("with __ImageBase = 0x%llx\r\n", (HINSTANCE)&__ImageBase);
printf("with mainCRTStartup = 0x%llx\r\n", mainCRTStartup);
return 0;
}
| Assuming you are using a recent version of Visual Studio your application is probably opted-in to ASLR (Address Space Layout Randomization) by default. This is a security feature that is designed to make it harder for shell code (exploits) to find places to latch on to.
Try adding the /FIXED linker switch, this will prevent your .EXE from having relocation information and in turn prevents ASLR from relocating your PE in memory. /DYNAMICBASE:NO is a weaker version of /FIXED that you can also try, especially for .DLLs.
|
69,115,373 | 72,677,372 | Case Sensitive Selection of Next Occurrence in Xcode | In Xcode, we can select the next occurrence of a selected sequence of characters by pressing Option + Command + E, but this finds the next occurrence of the selected text case-insensitively. How can we do this case-sensitively?
| Xcode version 13.4.1 has recently fixed this problem and Martin R's comment has become the solution. Now you can select a sequence of characters in your code and then press Option + Command + E to select the following occurrence of the sequence. You can repeatedly press the same key combination to select as many occurrences as desired, which is useful for quickly renaming variables or replacing a text pattern in the code with another text pattern. The search is performed case-sensitively if "Aa" is on, which can be set in the search box brought by pressing Command + F. If "Aa" is off, then the search is done case-insensitively; for example, if "RandomNumber" is selected, then pressing Option + Command + E would select "randomNumber" or "RandomNumber" as the next occurrence. When I asked this question, a case-insensitive search was performed always regardless "Aa" was on or off.
|
69,115,907 | 69,115,991 | Partially deduce arguments with constructor | Take the following class (C++17)
#include <variant>
template <typename Error, typename T>
class Optional
{
public:
constexpr Optional(T&& value)
: m_variant(std::forward<T>(value))
{}
private:
std::variant<Error, T> m_variant = Error{};
};
template <typename E, typename T>
Optional<E, T> MakeOptional(T&& val) { return Optional<E, T>{val}; }
enum class Error
{
ERROR,
OTHER_ERROR,
};
The following compiles just fine
Optional<Error, int> opt1{4};
auto opt3 = MakeOptional<Error>(7);
but this does not
Optional<Error> opt2{4}; // does not compile "too few template arguments for class template 'Optional'"
Is it possible to make the code above compile? It should be able to deduce the second template argument with the constructor's parameter just like MakeOptional() does.
| CTAD is a "all or nothing".
See the note
Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place.
|
69,116,414 | 69,118,533 | reduce response time while using async cpp boost socket | i've created an async beast server that gets a request from a browser, opens a second socket , writes the request , gets the response and sends it back to the browser. all async . as the "send back to browser" action waits to the read handler completion to trigger
void
on_write(
boost::system::error_code ec,
std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
if(ec)
return fail2(ec, "write");
std::cout << "===========on_write============" << std::endl;
stopper("async_write" , 0);
stopper("on_write" , 1);
// Receive the HTTP response
http::async_read(redirect_stream_, redirect_buffer_, redirect_res_,
std::bind(
&session2::on_read,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2));
}
void
on_read(
boost::system::error_code ec,
std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
if(ec)
return fail2(ec, "read");
std::cout << "===========on_read============" << std::endl;
stopper("on_write" , 0);
stopper("on_read" , 1);
// Write the message to standard out
std::cout << redirect_res_.base() << std::endl;
http::async_write(stream_, redirect_res_,
std::bind(
&session2::start_shutdown,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2));
// Gracefully close the stream
}
it seems (from checks i have done) that it takes to long before the "write to browser" action is triggered (the on_read function)
is there a better way to reduce the response to browser time? maybe by "read_some" method?
| Depends a lot on the goal. If you really wish to transparently relay request/response without any modification, then read_some will be a better approach (but you won't need anything from Beast, just Asio).
Using Beast, you can read partial requests as well, assuming you might want to modify some things about the messages being relayed, you might e.g. use message_parser<...> instead of message<> and use http::read_header and a loop to read a buffer_body.
There's an example in the docs that implements things like this: HTTP Relay example.
You can also search my answers: https://stackoverflow.com/search?q=user%3A85371+beast+read_header or for buffer_body and or request_parser/response_parser
Beyond that there are many small ways to reduce latency (proper planning of threads, executors, allocators). But for something like that you should probably post your code (to CodeReview?).
|
69,116,441 | 69,116,887 | Can't use glGenBuffers in .h file C++ | I'm trying to learn OpenGL in C++. To clean up my code I was trying to create an header file with all variables, which decribe objects, in it. This header looks something like this:
#pragma once
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <stb/stb_image.h>
namespace data {
...
float fragments[] = {...}
int indices[] = {...}
...
}
I would like to add to this namespace also VAOs and VBOs, but as soon as I try to implement them using glGenBuffers and glGenVertexArray:
unsigned int VBO;
glGenBuffers(1, &VBO);
the IDE (Visual Studio) points me an error out, which says "this declaration doesn't include storage class or type identifier" (referred to glGenBuffer function; my editor is set to Italian, hence my translation might not be berfect). I've also tried to add a class inside this namesace (even if in my starting plans I wanted to avoid this approach):
#include <...>
namespace data {
class Data {
public:
unsigned int VBO;
glGenBuffers(1, &VBO)
};
}
This time the error I get reads: "Missing explicit type. It is going to be used int" (referred to glGenBuffers function; holds what I wrote before: the translation might not be perfect, but I think it is understandable).
As a last attempt, I've tried to implement the namespace in the main.cpp file too, under the main function. The error I get is the same as the first one, but if I use these function calls inside main, they work. I've also already written some other classes, such as shader.h or camera.h following this guide, and there I was able (using necessary includes such as glad/glad.h) to use gl* functions such as glCreateShader, glCreateProgram, glAttachShader and so on.
| Snippet from OP:
namespace data {
class Data {
public:
unsigned int VBO;
glGenBuffers(1, &VBO)
};
}
This is a syntax error. glGenBuffers(1, &VBO) is a function call outside a function body block scope. You have to move it e.g. into the constructor of class Data. At best, you could put it into a lambda which is used as an initializer of Data::VBO:
namespace data {
class Data {
public:
unsigned int VBO
= []() { unsigned int VBO; glGenBuffers(1, &VBO); return VBO; }();
};
}
Looks a bit convoluted? As glGenBuffers() expects a pointer, the local variable VBO has to be used inside the lambda. It's value is returned to initialize the member var. VBO. Of course, I could've given the local var. yet another name…
Live Demo on coliru
|
69,116,792 | 69,119,007 | QGridLayout, tight rows and columns without padding or spacing | I am using QGridLayout, the first row has a QLabel which is used to show an icon set to 32x32 pixels. The next row has two QSvgWidgets, each of these is 16x14.
My code:
QGridLayout* pgrdloStatus(new QGridLayout);
if ( mplblStsIcon == nullptr )
{
mplblStsIcon = new QLabel();
}
if ( mpsvgRxIcon == nullptr )
{
mpsvgRxIcon = new QSvgWidget(":/SVG_LED");
mpsvgRxIcon->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
mpsvgRxIcon->setFixedSize(TraineeMonitor::mscuintCommsIconWidth,
TraineeMonitor::mscuintCommsIconHeight);
}
if ( mpsvgTxIcon == nullptr )
{
mpsvgTxIcon = new QSvgWidget(":/SVG_LED");
mpsvgTxIcon->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
mpsvgTxIcon->setFixedSize(TraineeMonitor::mscuintCommsIconWidth,
TraineeMonitor::mscuintCommsIconHeight);
}
const QString cstrToolTip(QString(
" %1: %2\r\n%3: %4")
.arg(tr("Hostname:")).arg(mstrHostname)
.arg(tr("MAC address:")).arg(mstrMACaddress));
mplblStsIcon->setToolTip(cstrToolTip);
pgrdloStatus->addWidget(mplblStsIcon, 0, 0, 1, 2, Qt::AlignHCenter);
pgrdloStatus->addWidget(mpsvgRxIcon, 1, 0, Qt::AlignLeft);
pgrdloStatus->addWidget(mpsvgTxIcon, 1, 1, Qt::AlignRight);
pgrdloStatus->setMargin(0);
pgrdloStatus->setSpacing(0);
return pgrdloStatus;
The result:
What I actually want is:
| I create this Example and add Items From the Designer to show you why you see that distance between icons.
I create GridLayout and put 2 labels and set 2 LED SVG image
this is what actually you do too :
But For Fixing this issue you should check this property :
which means this : label->setScaledContents(true);
Which means that your icons match to labels.
For removing margins of GridLay out you can also do this :
This is its code:
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QWidget *centralwidget;
QGridLayout *gridLayout;
QLabel *label;
QLabel *label_2;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
MainWindow->resize(207, 109);
centralwidget = new QWidget(MainWindow);
centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
gridLayout = new QGridLayout(centralwidget);
gridLayout->setSpacing(0);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
gridLayout->setContentsMargins(0, 0, 0, 0);
label = new QLabel(centralwidget);
label->setObjectName(QString::fromUtf8("label"));
label->setPixmap(QPixmap(QString::fromUtf8(":/icons/led-square-red.svg")));
label->setScaledContents(true);
gridLayout->addWidget(label, 0, 0, 1, 1);
label_2 = new QLabel(centralwidget);
label_2->setObjectName(QString::fromUtf8("label_2"));
label_2->setPixmap(QPixmap(QString::fromUtf8(":/icons/led-square-red.svg")));
label_2->setScaledContents(true);
gridLayout->addWidget(label_2, 0, 1, 1, 1);
MainWindow->setCentralWidget(centralwidget);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QCoreApplication::translate("MainWindow", "MainWindow", nullptr));
label->setText(QString());
label_2->setText(QString());
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
|
69,117,249 | 69,117,448 | Specifying noexcept function conditionally | Let's say I have such function declared noexcept:
int pow(int base, int exp) noexcept
{
return (exp == 0 ? 1 : base * pow(base, exp - 1));
}
From my very little, but slowly growing knowledge of C++, I can noexcept when I'm certain that function will not throw an exception. I also learned that it can be in some range of values, lets say that I consider my function noexcept when exp is smaller than 10, and base smaller than 8 (just as an example). How can I declare that this function is noexcept in such a range of values? Or the most I can do is leave a comment for other programmers that it should be within some certain ranges?
| You can use a condition for noexcept, but that condition must be a constant expression. It cannot depend on the value of parameters passed to the function, becaue they are only known when the function is called.
From cppreference/noexcept:
Every function in C++ is either non-throwing or potentially throwing
It cannot be both nor something in between. In your example we could make base a template parameter:
template <int base>
int pow(int exp) noexcept( base < 10)
{
return (exp == 0 ? 1 : base * pow<base>(exp - 1));
}
Now pow<5> is a function that is non-throwing, while pow<10> is a function that is potentially throwing.
|
69,117,264 | 69,117,875 | How to use CppFlow library with Visual Studio 2019? | I'm trying to make a system for traffic sign recognition. In order to be fast I decided to code image preprocessing and inference in C++ and training in Python. For training of CNN I use TensorFlow with Keras. I came to the part when I need to classify detected sign and for that I need to load my pretrained model. I would like to do it with CppFlow library, but I don't know how to use it with Visual Studio 2019. Can someone help me do it?
| I managed to figure it out. Part that confused me the most was that CppFlow is just a wrapper with headers, so you need CppFlow and TensorFlow C API. Also here is the link that helped me a lot with including dependencies in Visual Studio 2019: https://learn.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=msvc-160
|
69,117,426 | 69,117,519 | Template use without angle brackets - Overloading? | I'm a little confused about the idea of using template with <> brackets and without them. When I compiled the code I got the output I wasn't expecting, and didn't figure out why.
For example, let's say I have 2 functions and a template with the same prototype:
using namespace std;
template<typename T> void copy(T a, T b)
{
cout << "template copy" << endl;
}
void copy(int a, int b)
{
cout << "int copy" << endl;
}
void copy(string a, string b)
{
cout << "string copy" << endl;
}
And after compiling the main function:
int main()
{
copy<int>(1, 2);
copy<string>("ha", "ha");
copy("ab", "bc");
copy(1, 2);
return 0;
}
the output looked like this:
template copy
template copy
template copy
int copy
for the record all the code is written on the same CPP file.
| You have to remember that literal strings are really (constant) arrays of characters, which decays to (constant) pointers to char, i.e. const char*.
Since your function taking std::string arguments is not a direct match, and the compiler will not do a conversion, the template overload will be used (as copy<const char*>).
|
69,118,264 | 69,119,314 | How to combine projections with transform in C++20 ranges | C++20 ranges::sort supports projections, and that is great, but I want to do stuff that is more complex, in particular sort on result of function that operates on projected member.
For function call I tried the transform and then sort that view, but C++20 sort seems to not work on views, this answer explains why(for range-v3).
In other words can I write this without using a lambda/functor?
struct S{
int val;
};
int origin = 47;
// assume we can not change Distance to take S
int Distance(int val){
return std::abs(val - origin);
}
void my_sort(std::vector<S> ss) {
std::ranges::sort(ss, std::greater<>{}, [](const S& s){
return Distance(s.val);
});
}
| Seems like you want function composition:
void my_sort(std::vector<S>& ss) {
std::ranges::sort(ss, std::greater<>{}, compose(Distance, &S::val));
}
Where compose(f, g)(x) does f(g(x)). Boost.Hof has a compose, there's one in range-v3 somewhere too. Not one in the standard library though.
For function call I tried the transform and then sort that view,
There is a big difference between sort(r, less(), f) and sort(r | transform(f), less()): the former sorts r using the function f as the sort key, the latter sorts the transformed values specifically. A concrete example demonstrating the difference:
struct X {
int i;
int j;
};
vector<X> xs = {X{1, 2}, X{2, 1}, X{0, 7}};
// this would give you (0, 7), (1, 2), (2, 1)
// because we're sorting by the i
ranges::sort(xs, less(), &X::i);
// this would have given you (0, 2), (1, 1), (2, 7)
// because we're sorting the i's independently
ranges::sort(xs | views::transform(&X::i), less());
|
69,118,947 | 69,118,979 | Why isn't the cout overflow in this situation? | I have the following code patch running on my ubuntu20.04, compiled by gcc-9.
#include <iostream>
int main()
{
uint16_t a = 0xFFFF;
uint16_t b = 1;
uint16_t ret = a + b;
std::cout << a + b << std::endl;
std::cout << ret << std::endl;
}
I expect both of the results are overflowed, but the running results show that only the second one overflows and the first one can get correct result.
What makes them behave differently. The right value of the + operation should also be uint16_t, so why the first cout can get the right result?
P.S., when I change the type from uint16_t to uint32_t, both of them are overflowed.
| When you do a + b the operands will undergo arithmetic conversions which will promote the values to int types.
So a + b is really something like static_cast<int>(a) + static_cast<int>(b) and the result will of course be an int.
Promotion only happens with types smaller than int (so short or char). Values that already are int (or larger) will not be promoted.
|
69,119,344 | 71,597,396 | Raw output file got damaged | I’m working on oneVPL samples from this GitHub repository (https://github.com/oneapi-src/oneAPI-samples ) and I’m trying to build hello-vpp sample. After running the program with the command in readme.md file, I wanted to increase the video size to 1280x720. While playing the raw output file, I used the below command
fplay -video_size 1280x720 rawvideo out.raw
My raw output file got damaged. A buffered video got played. How do I change the width and height of the output file? Any suggestions here?
| Try the below command:
ffplay -video_size 1280x720 -pixel_format bgra -f rawvideo out.raw
|
69,119,418 | 69,122,281 | Issues with SendInput() | I was hoping to get some help with this piece of code.
#include <windows.h>
#include <thread>
void keyPress(WORD keyCode)
{
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wScan = keyCode;
input.ki.dwFlags = KEYEVENTF_SCANCODE;
SendInput(1, &input, sizeof(INPUT));
}
void keyRelease(WORD keyCode)
{
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wScan = keyCode;
input.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;
SendInput(1, &input, sizeof(INPUT));
}
void CtrlPress()
{
while (true)
{
if (GetAsyncKeyState(VK_RBUTTON)) {
Sleep(1000);
keyPress(0x1D);
Sleep(3000);
keyRelease(0x1D);
}
else {
keyRelease(0x1D);;
}
}
}
int main() {
CtrlPress();
}
Essentially, what I want it to do is to press Ctrl 1000ms after I press the right mouse button, and then keep it pressed for 3000ms, and then release it, and loop as long as the right mouse button is held down. I also want the loop to immediately stop and Ctrl to be let go if the right mouse button is let go.
However, something is wrong with the code, as it drastically slows down my PC as-is.
| Since you want the Ctrl key to be released immediately when the right mouse button is released, you really shouldn't be using Sleep() to pause the entire 1sec/3secs intervals on each loop iteration while the mouse button is down, otherwise you risk delaying up to 4secs after the mouse button is released before you can do anything again.
I would use a state machine for something like this, eg:
#include <windows.h>
void keyPress(WORD keyCode)
{
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wScan = keyCode;
input.ki.dwFlags = KEYEVENTF_SCANCODE;
SendInput(1, &input, sizeof(INPUT));
}
void keyRelease(WORD keyCode)
{
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wScan = keyCode;
input.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;
SendInput(1, &input, sizeof(INPUT));
}
enum myKeyState { IsUp, IsDown, WaitingForPress };
void CtrlPress()
{
myKeyState state = IsUp;
DWORD startTime = 0;
while (true)
{
if (GetAsyncKeyState(VK_RBUTTON) < 0) {
switch (state) {
case IsUp:
startTime = GetTickCount();
state = WaitingForPress;
break;
case IsDown:
if ((GetTickCount() - startTime) >= 3000) {
keyRelease(0x1D);
startTime = GetTickCount();
state = WaitingForPress;
}
break;
case WaitingForPress:
if ((GetTickCount() - startTime) >= 1000) {
keyPress(0x1D);
startTime = GetTickCount();
state = IsDown;
}
break;
}
}
else {
if (state == IsDown) {
keyRelease(0x1D);
state = IsUp;
}
}
Sleep(0); // to avoid CPU throttling
}
}
int main() {
CtrlPress();
}
That being said, rather than using GetAsyncKeyState() to poll the mouse status at regular intervals, I would instead suggest you ask the OS to notify you when the mouse status changes. In a console app, you can use SetWindowsHookEx() to install a WH_MOUSE or WH_MOUSE_LL hook for that purpose.
|
69,119,585 | 69,119,896 | Couldn't deuce template when I use type trait like technique in argument | I use some type trait like techniques to wrap the pointer and reference to improve its readability. I use ptr<T> to represent T*, and lref<T> to represent T&. I wrote codes below.
template <typename T>
struct ptr_impl {
using type = T*;
};
template <typename T>
using ptr = typename ptr_impl<T>::type;
template <typename T>
struct lref_impl {
using type = T&;
};
template <typename T>
using lref = typename lref_impl<T>::type;
It seemed to work fine until I wrote such a function
template <typename T, size_t N>
size_t CalculateArraySize(lref<T[N]>) {
return sizeof(T) * N;
}
I got compiler errors when I tried to pass a parameter like this
int arr[100];
lref<int[100]> p = arr;
CalculateArraySize(p);
Compiler(g++10) output err messages as below.
In function 'int main()':
/testcodes/test.cpp:122:23: error: no matching function for call to 'CalculateArraySize(int [100])'
122 | CalculateArraySize(p);
| ^
/testcodes/test.cpp:115:8: note: candidate: 'template<class T, long unsigned int N> size_t CalculateArraySize(lref<T [N]>)'
115 | size_t CalculateArraySize(lref<T[N]>) {
| ^~~~~~~~~~~~~~~~~~
/testcodes/test.cpp:115:8: note: template argument deduction/substitution failed:
/testcodes/test.cpp:122:23: note: couldn't deduce template parameter 'T'
122 | CalculateArraySize(p);
| ^
and I also try to overload another function without template, it works.
size_t CalculateArraySize(lref<int[100]>) {
return sizeof(int) * 100;
}
So why compiler can not deduce template parameter in such case?
| Your lref<T> is only an alias for a nested type lref_impl<T>::type, and types cannot be deduced from their nested types.
For example, if you have
template <typename T>
struct Identity { using type = T };
then the following will not be compiled:
template <typename T>
void f(typename Identity<T>::type t){}
void g(){f(1);}
|
69,119,777 | 69,120,315 | Fill two dimensional array with spiral | The task is to fill two dimens array [N][M] in a spiral with numbers starting with 1.
My code doesn't work when one of the elements (N or M) is odd or both are odd.
When I use two different even or two same even numbers it works.
I need help to do it so it would work in any case, with any N and M.
p.s. please keep my code (don't make dynamic array, keep defines and etc.)
https://pastebin.com/9HufHYBg
#include <iostream>
#define N 6
#define M 4
int nums = 1;
int p = 1;
int arr[N][M];
using namespace std;
void printArr(){
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
cout << arr[i][j] << "\t";
}
cout << endl;
}
}
void circle (int k){
// levo pravo
for (int i = 0+k; i < M-k; i++){
arr[N-N+k][i] = nums;
nums++;
}
// verh niz
nums--;
for (int i = 0+k; i < N-k; i++){
arr[i][M-1-k] = nums;
nums++;
}
// pravo levo
nums--;
for (int i = M-p; i >= 0+k; i--){
arr[N-1-k][i] = nums;
nums++;
}
// niz verh
nums--;
for (int i = N-p; i > 0+k; i--){
arr[i][0+k] = nums;
nums++;
}
p++;
}
int main(){
if (M<N){
for (int k = 0; k < M/2; k++){
circle(k);
}
} else {
for (int k = 0; k < N/2; k++){
circle(k);
}
}
printArr();
return 0;
}
| To summarise, I managed to solve using two changes:
first, we change the limits of the main call so that we reach the centre everytime, and second, we avoid overwriting of already populated indices. Here, I stop this overwriting by checking by using an if statement before every assignment. But, cleaner solutions might be possible for the same.
Tested for various combinations (odd-odd, even-even, odd-even, odd-odd-not-same, odd-odd-same etc..)
#include <iostream>
#define N 9
#define M 7
int nums = 1;
int p = 1;
int arr[N][M];
using namespace std;
void printArr(){
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
cout << arr[i][j] << "\t";
}
cout << endl;
}
}
void circle (int k){
// levo pravo
for (int i = 0+k; i < M-k; i++){
if (arr[N-N+k][i] == 0)
arr[N-N+k][i] = nums;
nums++;
}
// verh niz
nums--;
for (int i = 0+k; i < N-k; i++){
if (arr[i][M-1-k] == 0)
arr[i][M-1-k] = nums;
nums++;
}
// pravo levo
nums--;
for (int i = M-p; i >= 0+k; i--){
if (arr[N-1-k][i]==0)
arr[N-1-k][i] = nums;
nums++;
}
// niz verh
nums--;
for (int i = N-p; i > 0+k; i--){
if (arr[i][0+k] == 0)
arr[i][0+k] = nums;
nums++;
}
p++;
}
int main(){
if (M<N){
for (int k = 0; k < (M+1)/2; k++){
circle(k);
}
} else {
for (int k = 0; k < (N+1)/2; k++){
circle(k);
}
}
printArr();
return 0;
}
|
69,120,045 | 69,120,285 | Cast custom struct to another template type | template <typename T>
struct Colordata
{
public:
T *data;
unsigned long size;
unsigned long length;
template <size_t N>
Colordata(T (&arr)[N])
{
length = N;
size = sizeof(arr);
T dataArr[length];
for (int i = 0; i < N; i++)
{
dataArr[i] = arr[i];
}
data = dataArr;
}
template <typename TCast>
operator TCast() const
{
TCast dataCastTmp[length];
for (int i = 0; i < length; i++)
{
dataCastTmp[i] = (TCast)data[i];
}
return Colordata<TCast>(dataCastTmp);
}
};
int main(int argc, char const *argv[])
{
int arr[] = {12, 434, 54};
auto a = Colordata<int>(arr);
auto b = (float)a;
return 0;
}
When I tried to convert Struct<typename> to Struct<another typename> another typename doesn't exist. I think so 'cos I get error in the compiler log:
no matching function for call to «Colordata::Colordata(float [((const Colordata*)this)->Colordata::length])»
Is there any way to casting template struct to template struct?
| There are many problems with this code, but the one you asked about is happening because of the signature of the conversion operator:
template <typename TCast>
operator TCast() const
If you try to cast to a Colordata<float> then TCast will be the type Colordata<float>, and not float as the implementation assumes.
The solution is to only allow conversions to other Colordata instantiations:
template <typename TCast>
operator Colordata<TCast>() const
Now TCast will be float as desired, and you're one step closer to correct code.
The other problems are the use of variable-length arrays (not supported in C++), and storing pointers to local variables that outlive their scope leading to undefined behaviour. Use std::vector to make life easier and safer.
|
69,120,126 | 69,181,401 | How do I pass an array from Swift to MSL parameter (C++) | I want to make this custom CIFilter.
var dummyColors = [
CIVector(x: 0.9, y: 0.3, z: 0.4),
CIVector(x: 0.2, y: 0.5, z: 0.9),
CIVector(x: 0.5, y: 0.9, z: 0.3)
]
var normal = dummyColors.withUnsafeMutableBufferPointer { (buffer) -> UnsafeMutablePointer<CIVector> in
var p = buffer.baseAddress
print(p)
return p!
}
//this is parameter and how to pass bvalue to the kernel function
return self.kernel.apply(extent: inputExtent,
roiCallback: roiCallback,
arguments: [inputImage, reddish, greenish, blueish, normal]) // (5)
Here is me trying to pass parameter with pointer. However the code seem doesn't like it and it just crashed without no printing error.
And here is the metal function
extern "C" { namespace coreimage { // (3)
//this is how you define parameter on the top of the function
float4 dyeInThree(sampler src,
float3 redVector,
float3 greenVector,
float3 blueVector,
device float3 *a)
Is there another way how to pass the parameter to my metal code?
| I adopted this answer to your use case:
https://stackoverflow.com/a/58706038/16896928
Here's what I used for memory allocation:
var dummyColors = [
SIMD3<Float>(x: 1.1, y: 0.1, z: 0.1),
SIMD3<Float>(x: 0.1, y: 1.1, z: 0.1),
SIMD3<Float>(x: 0.1, y: 0.1, z: 1.1)
]
let pointer = UnsafeMutableRawPointer.allocate(
byteCount: 3 * MemoryLayout<SIMD3<Float>>.stride,
alignment: MemoryLayout<SIMD3<Float>>.alignment)
let sPointer = dummyColors.withUnsafeMutableBufferPointer { (buffer) -> UnsafeMutablePointer<SIMD3<Float>> in
let p = pointer.initializeMemory(as: SIMD3<Float>.self,
from: buffer.baseAddress!,
count: buffer.count)
return p
}
let data = Data(bytesNoCopy: sPointer, count: 3 * MemoryLayout<SIMD3<Float>>.stride, deallocator: .free)
You need to convert the buffer into NSData before passing it to the kernel. And here is the Metal function declaration:
extern "C" { namespace coreimage { // (3)
float4 dyeInThree(sampler src,
float3 redVector,
float3 greenVector,
float3 blueVector,
constant float3 a[]) {
Note the 'constant' namespace instead of 'device'. Otherwise the Metal compiler would give error at runtime.
|
69,120,164 | 69,120,223 | Why C++ standard split container class into multiple header file? | I've been learning C++ for a while and getting confused about its container usage. If I want to use certain container I have to manually include them one by one. For example, if I want to use "vector" container I have to type #include "vector", and if I need "list" container later I have to add #include "list".
Why wouldn't C++ standard simply put every container class inside one header file, like #include "container", so that developers could care less about including them one by one?
|
Why wouldn't C++ standard simply put every container class inside one header file, like #include "container", so that developers could care less about including them one by one?
Performance, specifically compile time performance. If you include everything, there is a lot of code that the compiler is going to have to deal with. If you only use 1% of everything, then 99% of the code the compiler is working with is useless to you and just wasting your time having the compiler deal with it.
|
69,120,221 | 69,120,340 | What conversion happens when we use "while" in C++? | I'm using the Microsoft documentation and cppreference as background. Microsoft's site says that the expression to be evaluated in while must be an integral type, a pointer type or some conversible to these. Cppreference's site although says that while expects a bool type expression.
What does really happen? The expression will be converted to bool or not necessarly?If I use, for example, a char type expression inside a while, wont it be necessary to be converted to bool?
| According for example to the C++ 14 Standard (6.4 Selection statements)
2 The rules for conditions apply both to selection-statements and to
the for and while statements
...The value of a condition that is an expression is the value of the
expression, contextually converted to bool for statements other than
switch; if that conversion is ill-formed, the program is ill-formed.
Here is a demonstrative program.
#include <iostream>
struct A
{
operator int() const { return 1; };
};
int main()
{
A a;
while ( a ) break;
return 0;
}
At first the object a is converted to the type int using the user defined conversion operator
operator int() const { return 1; };
After that there is applied the standard conversion from the type int to the type bool.
From the C++ 14 Standard (4 Standard conversions)
7 [ Note: For class types, user-defined conversions are considered as
well; see 12.3. In general, an implicit conversion sequence (13.3.3.1)
consists of a standard conversion sequence followed by a user-defined
conversion followed by another standard conversion sequence. — end
note ]
|
69,120,846 | 69,121,007 | Why am I getting a totally random number when trying to iterate through an array and adding up the sum by using sizeof()? | I am trying to get the size of an array, using that for the expression in my for loop, and getting a random sum when I compile.
#include <iostream>
int main()
{
int prime[5];
prime[0] = 2;
prime[1] = 3;
prime[2] = 5;
prime[3] = 7;
prime[4] = 11;
int holder = 0;
for (int i = 0; i < sizeof(prime); i++)
{
holder += prime[i];
}
std::cout << "The sum of the 5 prime numbers in the array is " << holder << std::endl;
}
The sum I get is 1947761361. Why is this? Shouldn't using the sizeof() function work here?
| The error is in your use of sizeof(). It returns the total size of what is passed in. You passed in an array of 5 integers. An int is typically 4 bytes, so your sizeof() should return 20.
The bare minimum fix is to change your for loop Boolean Expression:
i < sizeof(prime) becomes i < sizeof(prime) / sizeof(*prime)
It takes the total size of your array (20) and divides it by the size of the first element (*prime) to give you the number of elements in your array.
To explain a bit more about *prime, you need to understand that C-arrays decay to pointers to the first element if you look at them funny. The syntax here de-references the pointer and gives us the actual first element, an int. And so we get the size of an int.
All the stuff below is tangential to your actual question, but I like to put it out there.
Here's your code, squashing your array initialization and using a range-based for loop.
#include <iostream>
int main()
{
int prime[]{2, 3, 5, 7, 11}; // CHANGED: Declare and initialize
int holder = 0;
// CHANGED: Range-based for loop
for (auto i : prime) {
holder += i; // CHANGED: in a range-based for loop, i is the value of each
// element
}
std::cout << "The sum of the 5 prime numbers in the array is " << holder
<< std::endl;
}
The range-based for loop works here because the array is in the same scope as the array. If you were passing the C-array to a function, it wouldn't work.
Here's your code using a Standard Library function:
#include <iostream>
#include <iterator> // std::begin and std::end because C-array
#include <numeric> // std::reduce OR std::accumulate
int main() {
int prime[]{2, 3, 5, 7, 11};
std::cout << "The sum of the 5 prime numbers in the array is "
<< std::reduce(std::begin(prime), std::end(prime)) << std::endl;
}
The need for <iterator> is due to the fact that you are using a C-array. If we instead use a std::array or [better yet] std::vector, we can lose that requirement.
#include <iostream>
#include <numeric> // std::reduce
#include <vector>
int main() {
std::vector<int> prime{2, 3, 5, 7, 11};
std::cout << "The sum of the 5 prime numbers in the array is "
<< std::reduce(prime.begin(), prime.end()) << std::endl;
}
We got rid of the #include <iterator> requirement because std::arrays and std::vectors come with their own iterators. I also got rid of the holder variable completely, as there was no demonstrated need to actually store the value; so we print it directly.
NOTES: std::reduce() requires C++17, which any fairly recent compiler should provide. You could also use std::accumulate() if you wish.
You can specify that you're compiling C++17 code by passing -std=c++17 to the compiler. It's always a good idea to specify what C++ standard you expect your code to run against. And while we're talking about compiler flags, it's in your best interest to enable warnings with -Wall -Wextra at a minimum.
|
69,121,205 | 69,121,264 | C++, i use the function at() from Vector, but i have problem |
cannot convert '__gnu_cxx::__alloc_traits<std::allocator<std::__cxx11::basic_string<char> >, std::__cxx11::basic_string<char> >::value_type' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'gcc
sincerely i don't know why and how to correct this.
#include <stdio.h>
#include <conio.h>
#include <string>
#include <vector>
namespace anas
{
void passwordGenerator()
{
std::vector<std::string> PasswordString;
std::string ElencoAlfabeto("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
char CharAlfabeto[ElencoAlfabeto.length()];
for (int Lettere_Create = 0; Lettere_Create < 8; Lettere_Create++)
{
int NumeroCarattere = rand() % sizeof(CharAlfabeto);
CharAlfabeto [NumeroCarattere] = ElencoAlfabeto[NumeroCarattere];
PasswordString.push_back(CharAlfabeto[NumeroCarattere]);
}
for (int Lettere_Scritte = 0; Lettere_Scritte < 8; Lettere_Scritte++)
{
printf ( PasswordString.at(Lettere_Scritte) );
}
}
}
int main()
{
system("cls");
std ::printf("the program is started... \n \n");
anas::passwordGenerator();
}
the output should be a random 8 letter generator.
yes, this is my first time using vector ... here the article i use:
when i put the mouse-cursor on the at , i see 1 overload, what is mean overload?
| In this line
printf ( PasswordString.at(Lettere_Scritte) );
The function printf needs a const char* but your are giving it a std::string.
In addition to the type mismatch, you should never ever pass arbitrary data as the first parameter of printf, because it will try to interpret format codes.
If you really want to use printf, this will work:
printf( "%s", PasswordString.at(Lettere_Scritte).c_str() );
You can skip the format code decoding entirely using puts:
puts( PasswordString.at(Lettere_Scritte).c_str() );
Or you can use C++ iostreams, which know about std::string and don't need the c_str() call at all:
std::cout << PasswordString.at(Lettere_Scritte);
|
69,121,541 | 69,121,757 | What is the reason for core dump in my function (detect_duplicates) to be specific? | I have 3 functions here, and the compiler is going through the first 2 functions, but it is not entering the 3rd function(detect_duplicates).
#include <iostream>
using namespace std;
struct node {
int data;
struct node* next;
};
struct node* head = NULL;
void createLL(int a[], int n)
{
head = (struct node*)malloc(sizeof(struct node));
head->data = a[0];
head->next = NULL;
struct node *t, *last;
last = head;
for (int i = 1; i < n; i++) {
t = (struct node*)malloc(sizeof(struct node));
t->data = a[i];
t->next = NULL;
last->next = t;
last = t;
}
}
void printList(struct node* head_ref)
{
printf("Linked list : {");
while (head_ref != NULL) {
printf(" %d ", head_ref->data);
head_ref = head_ref->next;
}
printf("}\n");
}
void detect_duplicates(struct node* head, int size)
{
int x, y;
struct node *temp, *temp2;
temp = head;
cout << "Duplicate elements are : ";
for (int i = 0; i < size; i++) {
x = temp->data;
temp = temp->next;
temp2 = temp;
while (temp2->next != NULL) {
y = temp2->data;
if (x == y) {
cout << y << " ";
}
temp2 = temp2->next;
}
}
}
int main()
{
int Linked_list[30] = { 1, 2, 3, 4, 5, 1, 2, 4, 6, 7, 8 }, size = 11;
createLL(Linked_list, size);
cout << "Input ";
printList(head);
detect_duplicates(head, size);
return 0;
}
This is a program to detect the duplicate elements from an integer linked list. I can't figure out the error in my detect_duplicates function and also my compiler isn't showing a known error. It is just showing a Segmentation fault.
| When you want to access the next of temp2 in
temp2 = temp;
while (temp2->next != NULL) {
y = temp2->data;
if (x == y) {
cout << y << " ";
}
temp2 can be a nullptr which may cause a segmentation fault, because it points to nothing and you are trying to access it's member.
|
69,121,575 | 69,121,684 | How to catch std::variant holding wrong type in compile-time? | I have following piece of code:
#include <iostream>
#include <string>
#include <map>
#include <variant>
using namespace std;
template <class... Ts>
struct overloaded : Ts...
{
using Ts::operator()...;
};
template <class... Ts>
overloaded(Ts...)->overloaded<Ts...>;
using element_dict = std::map<string, string>;
using element_type = std::variant<string, element_dict, int>;
void foo(element_type elements)
{
std::visit(overloaded{
[](string element) { cout << "string\n"; },
[](element_dict element) { cout << "dict\n";},
[](auto /*elements*/) { throw std::runtime_error("wrong type"); }
}, elements);
}
int main()
{
element_type str_elems = "string_elem";
foo(str_elems);
element_type dict_elems = element_dict{ {"string", "string"} };
foo(dict_elems);
element_type wrong_type_elems = 5;
foo(wrong_type_elems); // throws error
return 0;
}
stdout :
string
dict
libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: wrong type
I have element_type containing several types. Basically I consider it to contain string and element_dict. Here I have situation when somebody added int type to element_type, but forgot to provide required fixes to foo function. Now I detect this situation in run-time throwing exception. Is there any way to detect it in compile-time?
| The easiest way to get that situation to fail at compile-time is to simply not include the overload lambda that catches non-string and non-element_dict typed items; that is, remove
[](auto /*elements*/) { throw std::runtime_error("wrong type"); }
Then it will fail at compile-time. Basically, by including that case, you are specifically telling the compiler that you want it to succeed at compiling such cases; you are opting-in to behavior you don't want.
|
69,121,697 | 69,123,238 | Short question about cin and input buffer | So, after learning a bit about the input stream and how the extraction operator works, is it basically okay to say this about the following code?
string a;
cin >> a;
This will basically extract whatever there is in the input stream, but if the stream is empty it basically asks the user to input something? Like is that right?
I used to think cin gives access to the input stream and the user can just types whatever and that gets extracted, but now that I understand it a bit more, is what I said true? It tries to extract something from the stream, but if it sees nothing there then it'll ask the user for input?
| std::cin is an object instance of the std::istream class, which has a std::streambuf object associated with it.
std::streambuf contains a memory buffer inside of it.
By default, std::cin uses an implementation of std::streambuf that reads from the calling process's STDIN stream.
When operator>> reads from std::cin, std::cin then reads data from its streambuf, which in turn reads from its memory buffer.
If that memory buffer does not contain enough data to satisfy the read, std::streambuf will read from its own input stream, placing new data into its memory buffer, repeating as needed until the requested read is satisfied. In your example, it will read from STDIN.
If that input stream does not have enough data to satisfy the read, it will wait for data to arrive, ie when the user types something into the console terminal. Or, if STDIN is redirected, when data arrives on the assigned pipe, or the pipe is closed.
|
69,121,718 | 69,121,772 | no suitable conversion function from "const std::string" to "char *" exists? | im trying to make a simple program that list all txt file in the directory then append hello world in them but i face an issue while passing the vector into WriteFiles Function
this is the following code i've tried to fix it for a while any oil be grateful for any help
#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <vector>
#include <iostream>
#include <windows.h>
#include <fstream>
using namespace std;
void ListFiles(vector<string>& f) // list all files
{
FILE* pipe = NULL;
string pCmd = "dir /b /s *.txt ";
char buf[256];
if (NULL == (pipe = _popen(pCmd.c_str(), "rt")))
{
return;
}
while (!feof(pipe))
{
if (fgets(buf, 256, pipe) != NULL)
{
f.push_back(string(buf));
}
}
_pclose(pipe);
}
void WriteFiles (const char* file_name)
{
std::ofstream file;
file.open(file_name, std::ios_base::app); // append instead of overwrite
file << "Hello world";
file.close();
}
int main()
{
vector<string> files;
ListFiles(files);
vector<string>::const_iterator it = files.begin();
while (it != files.end())
{
WriteFiles(*it); // the issue is here
cout << "txt found :" << *it << endl;
it++;
}
}
| WriteFiles(it->c_str()); will fix the problem. Iterators act a lot like pointers, so that's how you access a method indirectly.
|
69,121,733 | 69,121,894 | How to Understand "Pass By Reference Within a Function" w3schools example? | I'm having a hard time understanding how this example from the w3schools tutorial works.
#include <iostream>
using namespace std;
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
system("pause");
return 0;
}
I think I understand the first part:
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
I'm basically referencing whatever x and y are going to be when I call the function. So x is going to be "pointing" to firstNum and y is going to be pointing to secondNum. It's going to do the switcheroo using a third variable as a placeholder.
However, after I call the function swapNums(firstNum, secondNum);, I don't understand how the function with its local variables has the ability to change the values of int firstNum = 10; and int secondNum = 20;.
My understanding is that variables within a function are "local" and the scope of said variables only extend within the function itself. How do the local variables change other variables outside their own function without any return statements?
| Try this
#include <iostream>
void change_val_by_ref(int &x)
{
x=100
}
void change_val_by_val(int x)
{
x=50;
}
int main()
{
int whatever=0;
std::cout<<"Original value: "<<whatever<<"\n";
change_val_by_ref(whatever);
std::cout<<"After change by ref: "<<whatever<<"\n";
change_val_by_val(whatever);
std::cout<<"After change by val: "<<whatever<<"\n";
}
The output you will see is:
0
100
100
Let's see what happened
change_val_by_ref changed the original whatever, because the ref
was "pointing" to the VARIABLE.
change_val_by_val didn't change the whatever, because the argument of the function x has just copied the value of whatever, and anything that happens to x will not affect whatever, because they are not related.
That's the point of passing by ref.
|
69,121,803 | 69,121,984 | Array of objects being corrupted after using cout | After a few days of my question being closed, and my edits that would answer all of the questions in the comments not being approved, I have decided to re-post with a few changes.
I am new to c++, but I am an experienced programmer. I am trying to create a chess engine, as I have done it in python but I want it faster. I am storing my chess board as a 2d array of Piece pointers.
chessBoard.h
#include <iostream>
#include "pieces.h"
class Chess
{
private:
Piece* board[8][8] = {};
public:
Chess();
void print_board();
};
pieces.h
enum PieceType {
pawn, knight, bishop, rook, queen, king
};
enum Colour {
white, black
};
class Piece {
protected:
PieceType pieceType;
Colour colour;
public:
char symbol;
Piece(Colour colour);
};
class Pawn : public Piece {
public:
Pawn(Colour colour);
};
// The rest of the pieces are defined in the same way
pieces.cpp
#include "pieces.h"
Piece::Piece(Colour colour) {
this->colour = colour;
}
Pawn::Pawn(Colour colour) : Piece(colour) {
this->pieceType = pawn;
this->symbol = (colour == white) ? 'P' : 'p';
}
// The rest of the pieces constructors are the same
chessBoard.cpp
Chess::Chess()
{
// The back row of black pieces
Rook bq_r(black);
Knight bq_n(black);
Bishop bq_b(black);
Queen bq_q(black);
King bk_k(black);
Bishop bk_b(black);
Knight bk_n(black);
Rook bk_r(black);
board[0][0] = &bq_r;
board[0][1] = &bq_n;
board[0][2] = &bq_b;
board[0][3] = &bq_q;
board[0][4] = &bk_k;
board[0][5] = &bk_b;
board[0][6] = &bk_n;
board[0][7] = &bk_r;
}
void Chess::print_board() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j]) {
std::cout << board[i][j]->symbol;
std::cout << " ";
} else {
std::cout << ". ";
}
}
std::cout << std::endl;
}
}
main.cpp
#include "chessBoard.h"
int main()
{
Chess chess;
chess.print_board();
return 1;
}
I understand this is a lot of code, and I wish I could post only the relevant information, but unfortunately I have no clue what the problem was, and most of the comments on my last post asked for more info. If needed the complete code, it can be found here: https://github.com/kiran-isaac/chess-engine/tree/test.
The Expected Outcome
r n b q k b m r
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
The Actual Outcome
r � � � � r
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
The first rook is always correct. Everything after that changes with each running of the program.
The cause seems to be that the everything in the board array is corrupted. It is all fine until it hits the "printBoard" function. As soon as it encounters the first cout, everything in the array becomes corrupted. I can work around this by having it store the output in a string and outputting it afterwords, but this still causes the array to be corrupted, albeit after I have sucessfully printed it.
I hope that someone can help, as I am enjoying development with c++, and I don't want to give up on this project.
This is a screenshot of the value of the board array from line 1 of the printBoard() function. This is how it should be.
This is a screenshot from after the first iteration, after encountering the std::cout on line 4 of the printBoard() function.
I have been stuck on this problem for 2 days, researching and debugging, and I've found nothing. I'm sure it's something simple I'm doing wrong, I just can't find it. Please comment if you need any more info.
Thank you
| The objects bq_r etc. defined in your Chess::Chess() constructor have their lifetimes end when the constructor finishes, so the array is full of dangling pointers which can't validly be used.
I'd recommend instead:
#include <memory>
class Chess
{
private:
std::unique_ptr<Piece> board[8][8] = {};
public:
Chess();
void print_board();
};
Chess::Chess()
{
board[0][0] = std::make_unique<Rook>(black);
board[0][1] = std::make_unique<Knight>(black);
board[0][2] = std::make_unique<Bishop>(black);
board[0][3] = std::make_unique<Queen>(black);
board[0][4] = std::make_unique<King>(black);
board[0][5] = std::make_unique<Bishop>(black);
board[0][6] = std::make_unique<Knight>(black);
board[0][7] = std::make_unique<Rook>(black);
for (auto& pawn_pos : board[1])
pawn_pos = std::make_unique<Pawn>(black);
// ...
}
Since the unique_ptrs will clean up by deleting a pointer to base class Piece which actually points at other class types, that class needs a virtual destructor:
class Piece {
public:
// ...
virtual ~Piece() = default;
};
|
69,122,019 | 69,122,149 | Downcast with static cast | I have this hierarchy (methods are simplified):
struct BaseExpr {
explicit BaseExpr(ExprType expr_type) : expr_type_(expr_type) {}
virtual ~BaseExpr() = default;
template<typename T>
T const* As() const {
if (expr_type_ == T::expr_type) {
return static_cast<T const*>(this);
}
return nullptr;
}
ExprType expr_type_;
};
//CRTP
template<typename T>
struct Expr : public BaseExpr {
Expr() : BaseExpr(T::expr_type) {}
~Expr() override = default;
};
struct Variable : public Expr<Variable> {
static ExprType const expr_type = ExprType::kVariable;
// ...other methods
std::string name_;
};
Sometimes i need to downcast a pointer of a BaseExpr, to a concrete class, e.g. Variable, but i don't want to use dynamic_cast. So i store another static member (expr_type) for comparison purpose. Is this approach good? Or perhaps there a better of doing such thing?
| You are already paying for the cost of having a vtable, since you're using virtual functions and the like. So unless performance is a real problem (as evidenced by profiling), if you really, really need to do this (and you should definitely reconsider any code where you need to do this), just use dynamic_cast. It makes it clear that you're doing a thing that's at least somewhat dubious at the site where you're doing the operation.
Your method works only to the extent that:
You don't use multiple inheritance or virtual inheritance.
Everyone who creates a new type adds an appropriate value to ExprType (however that may work, whether an enum or some kind of hash).
|
69,122,226 | 69,123,821 | I want to make a C++ enum of QString formats to display a QTime | I've been working with C++ on a Time class in Qt and I need to write an enum class that contains the formats that I use in showTime(). Because of the nature of the QString formats I've been getting the following error, the value is not convertible to 'int'. I would gladly appreciate any help or suggestions.
P.S: Here's the code:
enum class TimeFormat {
a = "hh:mm:ss",
b = "hh:mm",
c = "H:m:s a"
};
class Time {
public:
Time();
~Time();
void setTime(QTime t);
QString showTime(){
return time->toString(format);
}
private:
QTime* time;
TimeFormat format;
};
| I used a switch statement
enum class TimeFormat {
format1,
format2,
format3,
};
class Time {
public:
Time();
~Time();
void setTime(int h, int m, int s);
QString showTime() const{
QString f;
switch (format) {
case TimeFormat::format1:
f="hh:mm:ss";
break;
case TimeFormat::format2:
f = "hh:mm";
break;
case TimeFormat::format3:
f= "H:m:s a";
break;
}
return time->toString(f);
}
void changeFormat(TimeFormat f);
private:
QTime* time;
TimeFormat format;
};
|
69,122,354 | 69,122,558 | Convert at::Tensor to double in C++ when using LibTorch (PyTorch) | In the following code, I want to compare the loss (data type at::Tensor) with a lossThreshold (data type double). I want to convert loss to double before making that comparison. How do I do it?
int main() {
auto const input1(torch::randn({28*28});
auto const input2(torch::randn({28*28});
double const lossThreshold{0.05};
auto const loss{torch::nn::functional::mse_loss(input1, input2)}; // this returns an at::Tensor datatype
return loss > lossThreshold ? EXIT_FAILURE : EXIT_SUCCESS;
}
| Thanks to GitHub CoPilot which recommended this solution. I guess I should leave my job now. :(
The solution is using the item<T>() template function as follows:
int main() {
auto const input1(torch::randn({28*28}); // at::Tensor
auto const input2(torch::randn({28*28}); // at::Tensor
double const lossThreshold{0.05}; // double
auto const loss{torch::nn::functional::mse_loss(input1, input2).item<double>()}; // the item<double>() converts at::Tensor to double
return loss > lossThreshold ? EXIT_FAILURE : EXIT_SUCCESS;
}
|
69,122,441 | 69,124,089 | UIAutomation missing to catch some elements | I'm using the code above to walk through the descendants of a window, however, it's not catching everything like I can see using inspect.exe.
Currently testing in the chrome browser, in this current webpage I'm writing this question, it's catching just current opened pages, bookmarks, and browser buttons, it's missing to catch the page content.
While testing in other windows like a folder, for example, it does catch everything correctly, but it's taking too much time, in a folder with 120 elements it takes up to 1.4 seconds, I wonder if the code could be improved in any manner?
#include <UIAutomation.h>
#include <UIAutomationCore.h>
#include <UIAutomationClient.h>
#include "Oleacc.h"
#include "atlbase.h"
#pragma comment(lib,"Oleacc.lib")
WCHAR window[250] = L"Ask a Question - Stack Overflow - Google Chrome";
IUIAutomationElement *element = GetTopLevelWindowByName(window);
ListDescendants(element, 2);
IUIAutomationElement* GetTopLevelWindowByName(LPWSTR windowName)
{
if (windowName == NULL)
return NULL;
CComPtr<IUIAutomation> g_pAutomation;
if (SUCCEEDED(CoInitialize(NULL)))
{
if (!SUCCEEDED(g_pAutomation.CoCreateInstance(CLSID_CUIAutomation8))) // or CLSID_CUIAutomation
return NULL;
}
VARIANT varProp;
varProp.vt = VT_BSTR;
varProp.bstrVal = SysAllocString(windowName);
if (varProp.bstrVal == NULL)
return NULL;
IUIAutomationElement* pRoot = NULL;
IUIAutomationElement* pFound = NULL;
IUIAutomationCondition* pCondition = NULL;
// Get the desktop element.
HRESULT hr = g_pAutomation->GetRootElement(&pRoot);
if (FAILED(hr) || pRoot == NULL)
goto cleanup;
// Get a top-level element by name, such as "Program Manager"
hr = g_pAutomation->CreatePropertyCondition(UIA_NamePropertyId, varProp, &pCondition);
if (FAILED(hr))
goto cleanup;
pRoot->FindFirst(TreeScope_Children, pCondition, &pFound);
cleanup:
if (pRoot != NULL)
pRoot->Release();
if (pCondition != NULL)
pCondition->Release();
VariantClear(&varProp);
return pFound;
}
void ListDescendants(IUIAutomationElement* pParent, int indent)
{
static CComPtr<IUIAutomation> g_pAutomation;
if (!g_pAutomation) {
if (SUCCEEDED(CoInitialize(NULL)))
{
if (!SUCCEEDED(g_pAutomation.CoCreateInstance(CLSID_CUIAutomation8))) // or CLSID_CUIAutomation
return;
}
}
if (pParent == NULL)
return;
IUIAutomationTreeWalker* pControlWalker = NULL;
IUIAutomationElement* pNode = NULL;
g_pAutomation->get_ControlViewWalker(&pControlWalker);
if (pControlWalker == NULL)
goto cleanup;
pControlWalker->GetFirstChildElement(pParent, &pNode);
if (pNode == NULL)
goto cleanup;
while (pNode)
{
BSTR sName;
pNode->get_CurrentName(&sName);
UIA_HWND uia_hwnd;
pNode->get_CurrentNativeWindowHandle(&uia_hwnd);
RECT rect;
pNode->get_CurrentBoundingRectangle(&rect);
ListDescendants(pNode, indent + 1);
IUIAutomationElement* pNext;
pControlWalker->GetNextSiblingElement(pNode, &pNext);
pNode->Release();
pNode = pNext;
}
cleanup:
if (pControlWalker != NULL)
pControlWalker->Release();
if (pNode != NULL)
pNode->Release();
return;
}
| Testing with Chrome version 93 and Windows 10:
If chrome window is at least partially visible, the first UIA child document in chrome is html page of the active tab, and you can walk the UIA elements in this page.
If chrome window is not visible, you cannot access the page content with UIA. You can only use UIA to access the main controls for Chrome, as explained here
You probably run the Inspect tool as small window in front of a partially visible Chrome window, so Inspect can see the page content. Otherwise there is nothing special about the Inspect tool.
Another quirk with Chrome is that when the Chrome window is in full-screen mode, the main controls are not seen by UIA. Instead only the page content is seen by UIA (as long as Chrome is not hidden behind another window)
This seems to be specific to Chrome. Firefox behaves as expected.
|
69,123,321 | 69,225,941 | QWebEngine view loads webpage slowly | I am loading a webpage using the QWebEngineView like
web_engine_view = new QWebEngineView();
QWebChannel* channel = new QWebChannel(web_engine_view->page());
web_engine_view->page()->setWebChannel(channel);
channel->registerObject(QString("my_object"), my_object);
m_web_engine_view->load("path/to/local/html");
The local html file looks like
<!DOCTYPE html>
<meta charset="utf-8">
<div id="my_div" style="width: 100%; height: 400px"></div>
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js">
</script>
<script>
new QWebChannel(qt.webChannelTransport, function (channel) {
let jsobject = channel.objects.my_object;
let json_string = jsobject.data;
// do stuff with the json string
});
</script>
The content of the .html file takes forever to render in my QT application. Does anyone know why this is the case? I am also rendering some OpenGL stuff in parallel. I am using QT 5.14.2.
| Updating my QT version to QT 5.15.0 made it much faster. Also, I had 3D OpenGLWidgets constantly rendering in parallel in my application. I had to make sure the rendering didn't get updated every frame. This significantly improved the performance of the QWebEngineView.
|
69,123,608 | 69,124,083 | c++ calculate the sum of two array's and output a boolean '0' if result even else '1' if odd |
I was hoping to find an alternative solution/method to mine for solving the above question given the set parameters. Essentially the way I went about it was to loop through the two arrays simultaneous and add the corresponding values. First place would have been to use a conditional operator.
#include <iostream>
#include <array>
using namespace std;
//an array of size 0 [no elements]
void myLists(int list1[], int list2[], int list3[], int size)
{
for (int i = 0; i < size; i++)
{
if ((list1[i] + list2[i]) % 2 == 0) // return the modulo of the two array sums
{
cout << (list3[i] == true);
}
else
{
cout << (list3[i] == false);
};
}
}
int main()
{
//initialize the two arrays
int list1[5]{1, 2, 3, 4, 5};
int list2[5]{0, 4, 6, 8, 10};
int list3[5]{};
int size{};
size = sizeof(list1) / sizeof(list1[0]);
myLists(list1, list2, list3, size);
return 0;
}
RESULTS OF CODE:
10101
| For starters the function should be declared like
void myLists( const int list1[], const int list2[], int list3[], size_t size ;
because neither the first parameter nor the second parameter are being changed within the function.
The function does not set elements of the third array. As the third array is zero initialized
int list3[5]{};
then this expression list3[i] == true always evaluates to false and this expression list3[i] == false always evaluates to true.
In fact you could write
if ((list1[i] + list2[i]) % 2 == 0) // return the modulo of the two array sums
{
list3[i] = list3[i] == true;
}
else
{
list3[i] = list3[i] == false;
};
or
list3[i] = (list1[i] + list2[i]) % 2 == 0 ? list3[i] == true : list3[i] == false;
But this looks clumsy and moreover in general this approach is incorrect and can result in undefined behavior because the user can pass an uninitialized array as the third argument.
It would be much better and correct to write
list3[i] = ( list1[i] + list2[i] ) % 2;
An alternative approach is to use the standard algorithm std::transform.
Here is a demonstrative program.
#include <iostream>
#include <algorithm>
void myLists( const int list1[], const int list2[], int list3[], size_t size )
{
std::transform( list1, list1 + size, list2, list3,
[] ( const auto &a, const auto &b )
{
return a % 2 ^ b % 2;
});
}
int main()
{
const size_t size = 5;
int list1[size] = { 1, 2, 3, 4, 5 };
int list2[size] = { 0, 4, 6, 8, 10 };
int list3[size];
myLists( list1, list2, list3, size );
for ( const auto &item : list3 )
{
std::cout << item << ' ';
}
std::cout << '\n';
return 0;
}
The program output is
1 0 1 0 1
In the return statement of the lambda expression there is used the logical XOR operator instead of the expression ( a + b ) % 2 to avoid integer overflow.
|
69,123,627 | 69,137,730 | Python ctypes returned c_char_p is corrupted | I have a C++ interface that contains the following:
extern "C"
{
char const* getValForEntry(Entry e)
{
std::string no_val = "__err::no_val";
if (handles.find(e) != handles.end())
{
std::string val = handles[e]->get_value();
return val.c_str();
}
else
return no_entry.c_str();
}
}
I have a python app that connects to this interface with ctypes like so:
self.lib.getUpdateForEntry.restype = c_char_p
val = self.lib.getUpdateForEntry(e)
The interface returns the string:
{"RVC HR1":{"Mode":1,"Seq Num":162,"Home":7,"Time":"Thu Sep 01 10:00:00 2000","Flags":0,"Data Len":1024,"Data":[26, ... an array of 1024 values ... ,239]}}
What the python app is seeing is:
p??"Mode":1,"Seq Num":162,"Home":7,"Time":"Thu Sep 01 10:00:00 2000","Flags":0,"Data Len":1024,"Data":[26, ... an array of 1024 values ... ,239]}}
The message is suppsosed to be a string with 2844 chars in it, but in python, the first 12 chars are always corrupted, and I see the message:
'utf8' codec can't decode byte 0xb1 in position 1: invalid start byte
If I adjust the message to only have a handful of values in the array (under 10) then the message is fine, but when I add more values, the first part of the message gets corrupted. Does anyone know why I am seeing this? Is there a max c_char_p length, or is it being returned as ascii and converted to unicode? Is it something else?
| See PaulMcKenzie and user4581301 comments above for explaination. The local variable val was going out of scope, which led to undefined behavior.
|
69,123,916 | 69,124,245 | Is there any way to hook insertion and deletion operations for the std containers? | Let's say, we are going to subclass the std::map and we need to catch all insertions and deletions to/from the container. For example, in order to save some application-specific information about the keys present in the container.
What's the easiest way to do this, if at all possible?
Probably, the most obvious way to do this is to override all methods and operators that perform the insertion and deletion. But I think, something may be easily lost sight of on this way, isn't it?
| There is no way to do that in the general case. Inheritance is not a good idea because std::map is not polymorphic and no virtual dispatch will happen when you use a pointer to a map. You might as well use a simple wrapper class at that point and save yourself a lot of hassle:
#include <iostream>
#include <map>
template <class Key, class Value>
struct Map {
private:
std::map<Key, Value> _data;
public:
template <class Y, class T>
void insert(Y &&key, T &&val) {
std::cout << "[" << key << "] = " << val << "\n";
_data.insert_or_assign(std::forward<Y>(key), std::forward<T>(val));
}
void remove(Key const &key) {
auto const it = _data.find(key);
if (it == _data.end())
return;
std::cout << "[" << key << "] -> removed\n";
_data.erase(it);
}
Value *get(Key const &key) {
auto const it = _data.find(key);
if (it == _data.end())
return nullptr;
return &it->second;
}
};
int main() {
Map<int, char const *> map;
map.insert(10, "hello");
map.insert(1, "world");
map.remove(1);
map.remove(10);
map.remove(999);
}
|
69,124,321 | 69,125,644 | (C++) Fastest way possible for reading in matrix files (arbitrary size) | I'm developing a bioinformatic tool, which requires reading in millions of matrix files (average dimension = (20k, 20k)). They are tab-delimited text files, and they look something like:
0.53 0.11
0.24 0.33
Because the software reads the matrix files one at a time, memory is not an issue, but it's very slow. The following is my current function for reading in a matrix file. I first make a matrix object using a double pointer, then fill in the matrix by looping through an input file .
float** make_matrix(int nrow, int ncol, float val){
float** M = new float *[nrow];
for(int i = 0; i < nrow; i++) {
M[i] = new float[ncol];
for(int j = 0; j < ncol; j++) {
M[i][j] = val;
}
}
return M;
}
float** read_matrix(string fname, int dim_1, int dim_2){
float** K = make_matrix(dim_1, dim_2, 0);
ifstream ifile(fname);
for (int i = 0; i < dim_1; ++i) {
for (int j = 0; j < dim_2; ++j) {
ifile >> K[i][j];
}
}
ifile.clear();
ifile.seekg(0, ios::beg);
return K;
}
Is there a much faster way to do this? From my experience with python, reading in a matrix file using pandas is so much faster than using python for-loops. Is there a trick like that in c++?
(added)
Thanks so much everyone for all your suggestions and comments!
| The fastest way, by far, is to change the way you write those files: write in binary format, two int first (width, height) then just dump your values.
You will be able to load it in just three read calls.
|
69,124,597 | 69,147,075 | How do I access the member `top` of a BIGNUM in OpenSSL 1.1.x? | I'm currently trying to port an old C++ project over from OpenSSL 1.0.2 to OpenSSL 1.1.1. It's worth noting that this is not my code, but from an open source project, and I can't tell exactly what this part is supposed to do.
One file uses this piece of code (simplified for this post):
BIGNUM *d; //Assume this is a valid, populated BIGNUM
int x = d->top;
Unfortunately, the BIGNUM structure is now opaque in OpenSSL 1.1.x, meaning its member, top, cannot be directly accessed anymore.
With that said, I have a few questions:
Is there a drop-in replacement I can use to access top?
What does top represent? (IIRC it holds the MSB of the bignum, but I can't find any place to confirm that)
Otherwise, is there a way I can avoid using top at all?
The code in question is available here, line 196 is where the first instance of d->top can be found.
The entire project is located in this repository.
| The full example you linked, copies out the bits from a BIGNUM (for the RSA d exponent) into a different structure. It does not only access d->top (which is the number of used chunks), but also d->d (the pointer to the actual chunks) as the source of the memcpy in the next line.
The canonical way to copy out the bits of a BIGNUM is bn2bin.
As for your specific questions:
Generally speaking, no, as its semantics refer to the internal representation. However, you can easily compute the required size from the BIGNUMs number of bits, which you already have access to.
The number of chunks used to store the BIGNUM
By exporting the function into an appropriately sized target buffer using an export function.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.