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,287,920 | 69,288,038 | Are addresses into constant vectors, inside a non-constant vector, stable? | If I have a std::vector<std::vector<char>>
Where the following is true:
The inner vectors's size is never changed
The outer vector's size is changed with insertions and removals
Can I take an address into the inner vector like this, use it after modifying the outer vector, and be safe?
std::vector<std::vector<char>> buffer;
#include <code that inserts into "buffer" uhhh 10 vectors with 100 char each>
char * ch = buffer[5].data();
// example of code that never erases/resizes the vector "ch" is pointing into...
// ... BUT will remove/insert vectors around it, prompting "buffer" to reallocate
buffer.erase(buffer.begin(), buffer.begin() + 4);
buffer.shrink_to_fit();
buffer.insert(buffer.begin(), std::vector<char>(1));
assert(buffer[1].data() == ch); // the 5th inner-vector moved to index 1
printf("how is this bit%c?", *ch); // but hopefully "ch" is still valid?
| If the outer vector has to grow, it will allocate a new buffer and move all of the inner vectors into that buffer. That means the addresses of those inner vectors will change but that does not mean the addresses of the buffers of the inner vectors will change. They will stay the same as vector is required to not invalidate any iterators/references/pointers to elements in the vector when it is moved.
|
69,287,923 | 69,288,709 | Dynamically Access Variable Inside a Struct C++ | I'm new to C++ and very confused on how to approach this. In Javascript, I can do something like this to access an object dynamically very easily:
function someItem(prop) {
const item = {
prop1: 'hey',
prop2: 'hello'
};
return item[prop];
}
In C++, I'm assuming I have to use a Struct, but after that I'm stuck on how to access the struct member variables dynamically.
void SomeItem(Property Prop)
{
struct Item
{
Proper Prop1;
Proper Prop2;
};
// Item[Prop] ??
}
This could be terrible code but I'm very confused on how to approach this.
| This is a simple example of how to create an instance of a struct and then access its members:
#include <iostream>
#include <string>
struct Item {
std::string prop1 = "hey";
std::string prop2 = "hello";
};
int main() {
Item myItem;
std::cout << myItem.prop1 << std::endl; // This prints "hey"
std::cout << myItem.prop2 << std::endl; // This prints "hello"
return 0;
}
As mentioned in the comments, it looks like you might want a map. A map has keys and values associated with them, as an example you could have a key "prop1" be associated with a value "hey":
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, std::string> myMap;
myMap["prop1"] = "hey";
myMap["prop2"] = "hello";
std::cout << myMap["prop1"] << std::endl; // This print "hey"
std::cout << myMap["prop2"] << std::endl; // This print "hello"
return 0;
}
The first would be considered "normal" struct usage in C++ and the other is more applicable to cases where you have to look things up by keys
|
69,287,967 | 69,288,029 | Can't bind winsock socket | I'm quite new to c++ networking so I've been watching some tutorials but I can't seem to find out why I can't bind my socket. Can someone explain to me what I'm doing wrong? Here's my code for binding the socket.
#include <stdlib.h>
#include <winsock2.h>
#pragma comment (lib,"ws2_32.lib")
#pragma warning( disable : 4996)
#define PORT 17027
int main()
{
//creating socket
SOCKET listenSocket = INVALID_SOCKET;
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//bind socket
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons(PORT);
int bindValue = bind(listenSocket, (struct sockaddr *)&address, sizeof(address));
if (bindValue == SOCKET_ERROR) {
std::cout << WSAGetLastError() << std::endl;
return 1;
}
Output: Could not bind: 10038
| You must state which interface you want to bind the socket to. This is done by setting the sin_addr member of the sockaddr_in structure.
For example, to bind to the wildcard interface INADDR_ANY (to be able to receive connections from all interfaces), you would do something like this:
address.sin_addr.s_addr = htonl(INADDR_ANY);
Whereas to bind to a specific interface, you would do something like this:
address.sin_addr.s_addr = inet_addr("interface IP here");
Regarding the error reporting, the Winsock API doesn't set errno for error (and errno is used by perror()). Instead, you need to use WSAGetLastError() to get the error code, and FormatMessage() to get the error description.
|
69,288,348 | 69,288,527 | Xcode development, can I place #pragma unused(x) via some #define rule | while developing in Xcode it is common to switch between Debug and Release mode and using some parts of code in Debug mode only while not using some in Release mode.
I often throw out NSLog code by some #define rule that lets the Pre-compiler parse out those commands that are not needed in a Release. Doing so because some final testing needs proof everything works as expected and errors are still handled properly without messing some NSLog i possibly forgot. This is in example of importance in audio development where logging in general is contra productive but needed while debugging. Wrapping everything in #ifdef DEBUG is kinda cumbersome and makes code lock wild, so my #defines are working well to keep code simple and readable without worrying about NSLog left in releases while still Logging on purpose if needed. This praxis works really well for me to have a proper test scenario with pure Release code.
But this leads to compiler warnings that some variables are not used at all. Which is not much of a problem but i want to go one step ahead and try to get rid of those warnings also. Now i could turn those warnings off in Xcode but i try to find a way to keep those and just getting rid of them for my NSLog overruled #defines
So instead of logging against dev>null i throw out (nullify) all code that is wrapped by NSLog(... ) and use some extra defined rule called ALLWAYSLog() that keeps NSLog in Releases on purpose and also changes NSLog to fprintf to avoid app origin and time prints.
Here my rules..
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr, "%s \n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String])
#else
#define NSLog(FORMAT, ...) {;}
#endif
#define ALLWAYSLog(FORMAT, ...) fprintf(stderr, "%s \n", [[[NSString alloc] initWithFormat:FORMAT, ##__VA_ARGS__] UTF8String])
To get rid of those unused variable warnings we often use
#pragma unused(variablename)
to inform the precompiler we did that on purpose..
Question:
Is it possible to write some #define rule that makes use of #pragma unused(x) ? Or how to integrate this mentioned way of __unused attribute
| In the #else case, you can put the function call on the right side of the && operator with 0 on the left side. That will ensure that variables are "used" while also ensuring that the function doesn't actually get called and that the parameters are not evaluated.
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr, "%s \n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String])
#else
#define NSLog(FORMAT, ...) (0 && fprintf(stderr, "%s \n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]))
#endif
|
69,288,932 | 69,289,383 | C++: Vector value resets efter exiting if-statement | I need to overwrite values in a 2D vector, where the new values is simply just equal to an integer I am counting up. But as soon as I exit this if-statement, the value resets to the original value? I think it may have something to do with the indexing, but I just can't figure it out
So I fill up the vector with either -1 or 0's
vector<vector<int>> P(225, vector<int>(225, 0));
for (int i = 0; i < 225; i++) {
for (int j = 0; j < 225; j++) {
if (img.at<uchar>(i, j) >= 220) {
P[i][j] = -1;
}
else {
P[i][j] = 0;
}
}
}
Where
img.at<uchar>(i, j)
is essentially just an array I check values from, with the same size as the vector. This works fine
Then I go through the vector again, to check for all -1's, and each time if either the vector index above or to the left of [i][j] is 0, I count up integer "bin", which I now want to place as the value on spot [i][j]
for (int i = 1; i < 225; i++) {
for (int j = 1; j < 225; j++) {
if ((P[i][j - 1] == 0) && (P[i - 1][j] == 0) && P[i][j] == -1) {
bin++;
P[i][j] = bin;
}
cout << P[i][j] << endl;
}
}
But right after it exits the if-statement, it just forgets the new value assigned to it? I know the bin integer goes up too, I have printed that out at well, so atleast some of the vector values should be changed, when the specific situation occurs. But they all just go back to 0's and -1's again, as if it never went through the if-statement
I hope my explanation is understandable
Minimalistic test-program: When I run this code that uses basic iostream components, same problem occurs. I think it may be a bug from my side at this point
#include <iostream>
using namespace std;
using namespace cv;
int main() {
int bin = 0;
vector<vector<int>> P(20, vector<int>(20, 0));
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if (j > 15) {
P[i][j] = 0;
}
if (j <= 14 && j >= 9) {
P[i][j] = -1;
}
if (j < 9) {
P[i][j] = 0;
}
}
}
for (int i = 1; i < 20; i++) {
for (int j = 1; j < 20; j++) {
if ((P[i][j-1] == 0) && (P[i-1][j] == 0) && P[i][j] == -1) {
bin++;
P[i][j] = bin;
}
cout << P[i][j] << endl;
}
}
}
| Here
if ((P[i][j - 1] == 0) && P[i][j] == -1) {
you are looking for a 0 that comes before -1, but you fill those vectors with -1 followed by 0
|
69,289,055 | 69,289,509 | Passing variables to a function with CreateRemoteThread | HANDLE CreateRemoteThread(
HANDLE hProcess,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId
);
lpParameter
A pointer to a variable to be passed to the thread function.
int x = 0;
LPCWSTR foo = L"Hello World";
CreateRemoteThread(hProcess, 0, 0, pFunction, &x, 0, 0);
Suppose i need to pass more than one variable, like x and foo, to a function that requires two parameters, example:
LPCWSTR Test(int x, LPCWSTR foo)
{
//....
}
How would it be?
| As its name implies, CreateRemoteThread() creates a new thread in an external process. As such, the lpStartAddress parameter must point to the memory address of a function in the target process, and the lpParameter parameter must point to a memory address that exists in the target process (unless it is a pointer-casted integer). You can't pass a pointer to memory that exists locally in the process that is calling CreateRemoteThread(). You can use VirtualAllocEx() to allocate memory in another process, eg:
DWORD WINAPI MyThreadProc(LPVOID lpParameter)
{
INT *x = (INT*) lpParameter;
// use *x as needed...
VirtualFree(x, 0, MEM_RELEASE);
return 0;
}
...
LPTHREAD_START_ROUTINE pFunction = ...; // point to MyThreadProc() in hProcess
INT x = 0;
LPVOID param = VirtualAllocEx(hProcess, NULL, sizeof(x), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!param) ...
SIZE_T numWritten;
if (!WriteProcessMemory(hProcess, param, &x, sizeof(x), &numWritten)) ...
if (!CreateRemoteThread(hProcess, 0, 0, pFunction, param, 0, 0)) ...
Alternatively, you can use a pointer-casted integer instead, in which case you don't need to allocate anything:
DWORD WINAPI MyThreadProc(LPVOID lpParameter)
{
INT x = INT(reinterpret_cast<INT_PTR>(lpParameter));
// use x as needed...
return 0;
}
...
LPTHREAD_START_ROUTINE pFunction = ...; // point to MyThreadProc() in hProcess
int x = 0;
LPVOID param = reinterpret_cast<LPVOID>(INT_PTR(x));
if (!CreateRemoteThread(hProcess, 0, 0, pFunction, param, 0, 0)) ...
If you need to pass multiple values to the function, you will have to allocate a struct in the target process to hold them, eg:
#pragma pack(push, 1)
struct MyThreadData
{
INT x;
LPCWSTR foo; // points to fooData...
//WCHAR fooData[]...
};
#pragma pack(pop)
...
DWORD WINAPI MyThreadProc(LPVOID lpParameter)
{
MyThreadData *params = static_cast<MyThreadData*>(lpParameter);
// use params->x and params->foo as needed...
VirtualFree(params, 0, MEM_RELEASE);
return 0;
}
...
LPTHREAD_START_ROUTINE pFunction = ...; // point to MyThreadProc() in hProcess
INT x = 0;
LPCWSTR foo = L"Hello World";
int foo_numBytes = (lstrlenW(foo) + 1) * sizeof(WCHAR);
MyThreadData *params = static_cast<MyThreadData*>(VirtualAllocEx(hProcess, NULL, sizeof(MyThreadData) + fooNumBytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (!params) ...
SIZE_T numWritten;
if (!WriteProcessMemory(hProcess, &(params->x), &x, sizeof(x), &numWritten)) ...
LPWSTR foo_data = reinterpret_cast<LPWSTR>(params + 1);
if (!WriteProcessMemory(hProcess, &(params->foo), &foo_data, sizeof(foo_data), &numWritten)) ...
if (!WriteProcessMemory(hProcess, fooDataPtr, foo, foo_numBytes, &numWritten)) ...
CreateRemoteThread(hProcess, 0, 0, pFunction, params, 0, 0);
|
69,289,061 | 69,289,354 | Linux isn't allowing to create enough sockets but not many sockets are being used | My C++ application creates 64-128 UDP sockets.
It creates sockets using this code:
int sock = socket(AF_INET, SOCK_DGRAM, 0);
assert(sock != -1, strerror(errno));
const u_int yes = 1;
int result = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
printf("sock=%i result=%i errno=%i\n", sock, result, errno);
if(result != 0)
{
FATAL(strerror(errno));
}
However, at the moment it's only creating 2 sockets because setsockopt() returns -1 on the third request:
sock=1023 result=-1 errno=0
(stderror(errno) just says success)
I'm puzzled because when I run ss it doesn't look like many sockets are in use:
ss -s
Total: 238
TCP: 85 (estab 16, closed 40, orphaned 0, timewait 37)
Transport Total IP IPv6
RAW 2 1 1
UDP 24 17 7
TCP 45 30 15
INET 71 48 23
FRAG 0 0 0
My understanding is you may have 1023 sockets. So the above implies I should be able to create 64-128?
How/what is the problem here?
| There is no limit on number of open sockets, but there is more general limit on number of opened file descriptors. The fact that it fails on fd=1023 suggests that this limit was truly hit, since on a typical Linux:
file descriptors are assigned consecutive numbers starting with 0
default limit (ulimit -n) is 1024 opened file descriptors
You can check the number of opened file descriptors with ls -l /proc/<pid>/fd | wc -l. I suspect that you have many opened (regular) files.
|
69,289,093 | 69,289,263 | Use TEXT function on variable c++ | I wanna use TEXT() on variable full code:
LPCTSTR data = TEXT(argv[0]);
Or if someone now how to write char variable to LPCTSTR.
| You can use ATL::CA2W:
#include <iostream>
#include <Windows.h>
#include <atlbase.h>
#include <atlconv.h>
int main(int argc, char* argv[]) {
LPCSTR lpcstr = argv[0];
ATL::CA2W wtext(lpcstr);
LPCTSTR lpctstr = wtext.m_psz;
std::wcout << lpctstr << std::endl;
return EXIT_SUCCESS;
}
|
69,290,306 | 69,290,505 | Why is reading char by char faster than iterating over whole file string? | I have a lexer that consumes a file character by character, looking for tokens. I tried two methods for NextChar(), the first reads directly from ifstream through ifstream::get(ch), and the second loads the whole file into a std::stringstream to avoid disk I/O overhead.
get() method:
inline void Scanner::NextChar()
{
inputStream.get(unscannedChar);
currentCol++;
while (unscannedChar == ' ')
{
inputStream.get(unscannedChar);
currentCol++;
}
if (inputStream.eof()) {
unscannedChar = std::char_traits<char>::eof();
}
}
stringstream method:
while loading the file into stringstream takes no time, indexing is extremely slow.
inline void Scanner::NextChar()
{
unscannedChar = buffer.str()[counter++];
currentCol++;
while (unscannedChar == ' ')
{
unscannedChar = buffer.str()[counter++];
currentCol++;
}
if (counter > buffer.str().size())
{
unscannedChar = std::char_traits<char>::eof();
}
}
I expected the 2nd method to be much faster, since it's iterating over characters in memory not on disk, but I was wrong, and here are some of my tests:
| tokens | ifstream::get() | stringstream::str()[] |
|-------- |----------------- |----------------------- |
| 5 | 0.001 (sec) | 0.001 (sec) |
| 800 | 0.002 (sec) | 0.295 (sec) |
| 21000 | 0.044 (sec) | 693.403 (sec) |
NextChar() is extremely important for my project, and I need to make it as fast as possible and I would appreciate explaining why am I having the previous results?
| std::ifstream is already doing its own internal buffering, so it's not like it has to go out and wait for the hard drive to respond every time you call get(ch); 99.99% of the time, it already has your next character available in its internal read-buffer and just has to do a one-byte copy to hand it over to your code.
Given that, there's no additional speedup to be gained by copying the entire file into your own separate RAM buffer; indeed, doing that is likely to make things slower since it means you can't start parsing the data until after the entire file has been read into RAM (whereas with ifstream's smaller read-ahead buffer, your code can start parsing chars as soon as the first part of the file has been loaded, and parsing can continue to some extent in parallel with disk reads after that)
On top of that, stringstream::str() is returning a string object by-value every time you call it, which can be very expensive if the returned string is large. (i.e. you are making an in-RAM copy of the file's contents, and then throwing it away, for every character you parse!)
|
69,290,946 | 69,292,200 | How do I memoize this program? | PepCoding | Count Binary Strings.
You are given a number n.
You are required to print the number of binary strings of length n with no consecutive 0's.
My code:
void solve(int n ,string ans , vector<string> &myAns){
if(ans.size()==n) {
//cout << ans << "\n";
myAns.push_back(ans);
return;
}
if(ans.back() == '0'){
solve(n , ans + "1" , myAns);
}
else{
solve(n , ans + "0" , myAns);
solve(n , ans + "1" , myAns);
}
}
How should I store the recurring strings, in a hash or something?
| Note that you are required to print the number of binary strings of length n with no consecutive 0's, not to actually form (and store or print) all of them.
So, yes, a recursive solution could greatly benefit from memoization, but not of all the single strings. What you should store is the number of strings for each length. Two numbers, actually, one of the strings preceded by a 1 and one of those preceded by a 0.
long long solve(long long n, bool is_previous_a_zero = false)
{
// Memoize the number of strings for each length and
// possible previous character.
using key_t = std::pair<long long, bool>;
static std::map<key_t, long long> mem{
{{1, false}, 2}, // "0", "1"
{{1, true}, 1} // "1" after a "****0"
};
if ( n < 1 ) {
return 0;
}
// First check if the result is already memoized.
key_t key{ n, is_previous_a_zero };
auto const candidate = mem.lower_bound(key);
if( candidate != mem.cend() and candidate->first == key ) {
return candidate->second;
}
// Otherwise evaluate it recursively and store it, before returning.
long long result = is_previous_a_zero
? solve(n - 1, false)
: solve(n - 1, true) + solve(n - 1, false);
mem.emplace_hint(candidate, key, result);
return result;
}
Here this approach is tested for all the lengths up to 45.
Note that if you are interested only in runtime efficiency you can just precalculate all those numbers at compile time.
template< std::size_t N >
constexpr auto make_lut()
{
std::array<long long, N + 1> lut{0, 2, 3};
for ( size_t i = 3; i <= N; ++i) {
lut[i] = lut[i - 1] + lut[i - 2]; // Yeah, it's a Fibonacci sequence.
}
return lut;
}
// Then it can be called like so
constexpr auto lut{ make_lut<45>() };
// The number of binary strings of length n with no consecutive 0's = lut[n];
You can test it here.
To prove that the last snippet really solves the posted problem, consider theese points:
There are only 2 possible binary strings of length 1: "0" and "1".
There are 3 possible binary strings of length 2 with no consecutive 0's: "01", "10" and "11".
All the possible strings of length n are all the strings composed prepending a "1" to all the strings of length n - 1, plus all the strings composed prepending "01" to all the strings of length n - 2. Any other combination would result in consecutive zeroes.
|
69,290,986 | 69,299,250 | GDB keeps downloading debug info | Every now and then, when I launch a debug process, GDB starts by downloading all debug info for all dependencies, which is not negligeable. Given the fact that dependencies don't get added THAT often, I suspect it's because I am using rolling distro, so every time I perform a distribution upgrade, GDB will re-downloads debug info upon next launch (might be completely wrong on that one, I don't know)
After looking into documentation, I tried:
...
Downloading separate debug info for /lib64/libFLAC.so.8...
Downloading separate debug info for /lib64/libspeex.so.1...
Downloading separate debug info for /lib64/libopus.so.0...
...
(gdb) show debug-file-directory
The directory where separate debug symbols are searched for is "/usr/lib/debug".
...
# Huh?
denis@localhost:~> file /usr/lib/debug
/usr/lib/debug: cannot open `/usr/lib/debug' (No such file or directory)
denis@localhost:/usr> sudo find . -name debug
./share/code/resources/app/out/vs/workbench/contrib/debug
./include/c++/10/debug
./include/c++/11/debug
./src/linux-5.13.13-1/arch/arm/include/debug
./src/linux-5.13.13-1/kernel/debug
./src/linux-5.13.13-1/tools/power/cpupower/debug
./src/linux-5.14.0-3.g501d1f1/arch/arm/include/debug
./src/linux-5.14.0-3.g501d1f1/kernel/debug
./src/linux-5.14.0-3.g501d1f1/tools/power/cpupower/debug
./lib64/node_modules/npm16/node_modules/debug
denis@localhost:/usr>
How do I download and store, and adjust GDB to use the same debug info?
If that's of any importance, I am using openSUSE Tumbleweed
| GDB uses debuginfod_find_debuginfo() to find and download the debug info files. Documentation says:
debuginfod_find_debuginfo(), debuginfod_find_executable(), and debuginfod_find_source()
query the debuginfod server URLs contained in $DEBUGINFOD_URLS
(see below) for the debuginfo ...
...
CACHE
If the query is successful, the debuginfod_find_*() functions save the target
file to a local cache. The location of the cache is controlled by the
$DEBUGINFOD_CACHE_PATH environment variable (see below).
Cleaning of the cache is controlled by the cache_clean_interval_s and
max_unused_age_s files, which are found in the $DEBUGINFOD_CACHE_PATH directory.
cache_clean_interval_s controls how frequently the cache is traversed for cleaning
and max_unused_age_s controls how long a file can go unused
(fstat(2) atime) before it's removed from the cache during cleaning.
So it seems like you are suffering from either too frequent cleaning, or too low max_unused_age_s setting.
And unsetting DEBUGINFOD_URLS in the environment should stop GDB from downloading anything.
|
69,291,130 | 69,291,650 | What's wrong with my c++ code? for a = 90 Z should be equal to -1, but I'm getting completly different answer. Why? | I tried to make code that can calculate trigonometric function but it went wrong and i don't know what to do because I just can't see any mistakes
using namespace std;
#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <iostream>
#include <conio.h>
#include <cmath>
int main()
{`
const double pi = M_PI;
double Z, a, sin1, cos1, X, Y;
//printf("Input a =");
printf("%s", "Input a = ");
scanf("%g", &a);
a = a * pi / 180;
sin1 = sin(3 * pi - 2 * a);
X = (sin1 * sin1)*2;
cos1 = cos(5 * pi - 2 * a);
Y = cos1 * cos1;
Z = X - Y;
printf("Z = %g\n\n", Z);
_getch();
return 0;
}`
| As mentioned in the above commments, enabling compiler warning messages should indicate the problem and suggest a solution, thus removing _CRT_SECURE_NO_WARNINGS may help to view the problem and solution:
(15,11): warning C4477: 'scanf' : format string '%g' requires an argument of type 'float *', but variadic argument 1 has type 'double *'
(15,11): message : consider using '%lg' in the format string
(15,5): error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
When using the compiler suggestion:
scanf("%lg", &a);
as also mentioned in the above comments, we still get a warning regarding use of scanf:
(15,5): error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
So, to keep using scanf when we include _CRT_SECURE_NO_WARNINGS and get expected output, however using the compiler suggested scanf_s (and remove _CRT_SECURE_NO_WARNINGS) also produces expected output.
However, since you've included iostream, c++ provides the cin object of class iostream, thus the simplest solution may be to use cin as suggested in the above comment.
|
69,291,136 | 69,291,403 | Finding the longest palindromic substring (suboptimally) | I'm working on a coding exercise that asks me to find the longest palindromic substring when given an input string. I know my solution isn't optimal in terms of efficiency but I'm trying to get a correct solution first.
So far this is what I have:
#include <string>
#include <algorithm>
#include <iostream>
class Solution {
public:
string longestPalindrome(string s) {
string currentLongest = "";
for (int i = 0; i < s.length(); i++)
{
for (int j = i; j <= s.length(); j++)
{
string testcase = s.substr(i, j);
string reversestring = testcase;
std::reverse(reversestring.begin(), reversestring.end());
if (testcase == reversestring)
{
if (testcase.length() > currentLongest.length())
{
currentLongest = testcase;
}
}
}
}
return currentLongest;
}
};
It works for several test cases, but also fails on a lot of other test cases. I suspect something is going wrong in the most inner loop of my code, but am not sure exactly what. I'm attempting to generate all possible substrings and then check if they are palindromes by comparing them with their reverse; after I establish they are a palindrome I check if it's longer than the current longest palindrome I have found.
| because you are not trying all the possible solution
in c++ , substr takes two parameters the first are the starting index , and the second is the length of the substring
how ever in you program you don't check for the string which starts at index 4 and have length of three for example
in the second for loop you shoud start from index 1 not from index i
|
69,291,570 | 69,291,592 | How can I use structured bindings to set an array's values? | I'm new to C++17 and I ran into a problem when I tried to use structure binding to set values to a couple of array cells. But the regular syntax doesn't work here; it gets confused with the array's brackets.
How can I solve it? Is it even possible?
Example:
std::pair<int, int> makePair() {
return { 10, 20 };
}
int main() {
int arr[20];
// error here
auto [arr[0], arr[1]] = makePair();
}
| It is the wrong tool for the job. Structured bindings always introduce new names; they don't accept arbitrary expressions for lvalues.
But you can do what you want even in C++11. There's std::tie, for this exact purpose:
std::tie(arr[0], arr[1]) = makePair();
Give it a bunch of lvalues for arguments, and it will produce a tuple of references to them. std::tuple interacts with std::pair (considered as two-tuple), and the member-wise assignment modifies the array elements you named.
|
69,292,169 | 69,292,449 | How to send a pointer to another thread? | I created a Rust wrapper for a C++ library for a camera using bindgen, and the camera handle in the C++ library is defined as typedef void camera_handle which bindgen ported over as:
pub type camera_handle = ::std::os::raw::c_void;
I'm able to successfully connect to the camera and take images, however I wanted to run code on a separate thread for temperature control of the camera, essentially changing the cooler power based on the current temperature of the camera, which I want to have run separately from the rest of the code. These calls require the camera handle, but when I spawn a new thread, I keep getting the error:
'*mut std::ffi::c_void' cannot be sent between threads safely
And underneath it, it mentions:
the trait 'std::marker::Send' is not implemented for '*mut std::ffi::c_void'
How can I send this to another thread so I can use this camera handle there as well? I have tried using fragile and send_wrapper, but have been unsuccessful with both of them.
| Pointers do not implement Send or Sync since their safety escapes the compiler. You are intended to explicitly indicate when a pointer is safe to use across threads. This is typically done via a wrapper type that you implement Send and/or Sync on yourself:
struct CameraHandle(*mut c_void);
unsafe impl Send for CameraHandle {}
unsafe impl Sync for CameraHandle {}
Since implementing these traits manually is unsafe, you should be extra diligent to ensure that the types from the external library actually can be moved another thread (Send) and/or can be shared by multiple threads (Sync).
If you ever take advantage of the pointer's mutability without the protection of &mut self, it should probably not be Sync since having two &mut T at the same time is always unsound.
See:
Send and Sync in the Rustonomicon.
Can a struct containing a raw pointer implement Send and be FFI safe?
|
69,292,694 | 69,292,705 | How to delete all files in a certain folder | I'm trying to make a feature in my program to delete all files in the Windows temporary folder "(C:\Users\Owner\AppData\Local\Temp)", how would I do this?
| Call the Win32 API GetTempPath() function to get the user's %TEMP% folder path, then you can either:
call FindFirstFile()/FindNextFile() in a loop, calling DeleteFile() on each iteration.
call SHFileOperation(), specifying FO_DELETE with a *.* wildcard.
use a loop to discover the files, calling IFileOperation::DeleteItem() to mark each one for deletion, and then call IFileOperation::PerformOperations() to actually delete them.
If you want a pure C++ solution, and are using C++17 or later, then you can use std::filesystem::temp_directory_path(), using std::filesystem::directory_iterator and std::filesystem::remove() in a loop, or just std::filesystem::remove_all() by itself.
|
69,292,807 | 69,292,936 | Blocking mouse messages with hook | How do i 'block' the WM_LBUTTONDOWN message to be fired?
The function is inside of a dll, I also tried to use LowLevelMouseProc but it does not work with error code: 1429 which means "global only hook".
I don't own the window in question.
I tried to return a WM_NULL in the code below, but it also doesn't work, what else i could try?
extern "C" __declspec(dllexport) LRESULT CALLBACK mouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
MSLLHOOKSTRUCT* mhs = nullptr;
int x = 0;
int y = 0;
std::wstringstream ss;
std::wstringstream ss2;
if (nCode == HC_ACTION)
{
switch (wParam)
{
case WM_LBUTTONDOWN:
ss << L"\nWM_LBUTTONDOWN " << wParam;
wParam = WM_NULL;
break;
case WM_LBUTTONUP:
ss << L"\nWM_LBUTTONUP " << wParam;
break;
case WM_MOUSEMOVE:
break;
case WM_RBUTTONDOWN:
ss << L"\nWM_RBUTTONDOWN: " << wParam;
break;
case WM_RBUTTONUP:
ss << L"\nWM_RBUTTONUP: " << wParam;
break;
default:
ss << L"\nUnknown msg: " << wParam;
break;
}
}
OutputDebugString(ss.str().c_str());
mhs = reinterpret_cast<MSLLHOOKSTRUCT*>(lParam);
x = mhs->pt.x;
y = mhs->pt.y;
ss2 << L"\nx: " << x << L" y: " << y;
OutputDebugString(ss2.str().c_str());
return CallNextHookEx(NULL, nCode, wParam, lParam);
| Per the MouseProc callback function documentation:
If nCode is greater than or equal to zero, and the hook procedure did not process the message, it is highly recommended that you call CallNextHookEx and return the value it returns; otherwise, other applications that have installed WH_MOUSE hooks will not receive hook notifications and may behave incorrectly as a result. If the hook procedure processed the message, it may return a nonzero value to prevent the system from passing the message to the target window procedure.
As for your WH_MOUSE_LL error, you can't install that hook on a thread-specific basis, only globally.
|
69,292,860 | 71,501,801 | How can I get "go to definition" working in a JUCE project? | I'm trying to get "go to definition" working for a JUCE project created with Projucer. I've tried both CLion and Visual Studio Code, but they can't seem to find definitions that live in the JUCE libraries.
I'm on Ubuntu. Is there a blessed path for this? I'm normally a vim user, but I'm willing to try any IDE.
| What I ended up doing was using FRUT to convert my project from a Projucer project to a CMake project. CLion was able to understand the CMake project, and thus, the "go to definition" and autocomplete features started working.
|
69,293,016 | 69,293,076 | Not understanding std::filesystem::directory_iterator | I just started looking into C++ and have been reading a book and am only a couple of chapters in.
I thought a good exercise would be to print out a directory. When I look it up, I see this nice for loop that is driving the train from.
for (const auto & entry : fs::directory_iterator(path))
std::cout << entry.path() << std::endl;
My next logical step was going to store these values in a vector or an array.
For the past three hours, I have not been able to figure it out. What is entry? Is it a constant? Is it a string? What's stopping me from placing it in a vector? I can't get this code to run.
I am sorry for the basic question, I just need some conceptual clarification.
This is my code, push_back() does not take constants and I can't convert the constants to a string. What am I missing?
auto filepath()
{
std::vector <string> lis;
std::string path = "C:/Users/Derek Comeau/3D Objects";
for (const auto& entry : filesystem::directory_iterator(path)) {
const string paths = entry.path();
lis.push_back(paths);
}
}
| A Range-based for loop iterates through a container using its iterators. In this case, there is no container, directory_iterator acts stand-alone.
When the directory_iterator is constructed, it finds the first file in the specified folder. When the loop dereferences the iterator via its operator*, it returns a const directory_entry& to the current file. When the loop advances the iterator via its operator++, it advances to the next file. Repeating until there are no more files to report.
The directory_entry::path() method returns a const path&, not a std::string. However, the path::string() method returns a std::string.
std::vector does not have a pushback() method. The correct name is push_back().
With that said, try this instead:
auto filepath()
{
vector<std::string> lis;
std::string folder = "C:/Users/Derek Comeau/3D Objects";
for (const auto& entry : std::filesystem::directory_iterator(folder)) {
lis.push_back(entry.path().string());
}
return lis;
}
|
69,293,045 | 69,293,122 | Moving from pair/tuple elements via structured binding | Given std::pair<std::set<int>, std::set<int>> p, what is the right syntax to move its elements via structured binding?
How to do
std::set<int> first_set = std::move(p.first);
std::set<int> second_set = std::move(p.second);
via structured binding syntax? Is the following equivalent to the above?
auto&& [first_set, second_set] = p;
|
Is the following equivalent to the above?
No, there is no move operation, only the member variable of p is bound to the lvalue reference first_set and second_set. You should do this:
auto [first_set, second_set] = std::move(p);
|
69,293,214 | 69,293,250 | Why does my function always return 0 instead of returning the sum result? | I just started learning C++, now I'm making a simple array sum function.
Why is my code output always 0? Does it mean that my function returns "0"?
If I put cout in the function, it shows the right sum result.
#include <iostream>
using namespace std;
int ArraySum(int arr[], int size){
int sum=0;
for(int i=0 ; i<size; i++){
cin >> arr[i];
sum +=arr[i];
}
return sum;
}
int main()
{
int n, sum;
cin >>n;
int arr[n];
ArraySum(arr, n);
cout << sum;
return 0;
}
| You are not assigning the return value to the sum when it is returned.
You have 2 options:
pass a pointer to the sum, and dereference it inside ArraySum()
assign the value that is returned by ArraySum() to the sum int.
|
69,293,309 | 69,293,338 | Private member c++ problems | I've run into an error that I don't know how to fix. My program does not compile because it outputs "declared private here". Not sure how to fix this, looking for feedback in order to improve my skills! Thanks in advance.
I've only included the areas where I am experiencing issues.
class List
{
public:
List() { first = NULL; } // constructor
List(const List& source); // copy constructor
~List(); // destructor
int length() const; // returns the length of the list that invokes it
bool present(const int& target) const;
void insert(const int& entry); // inserts the item n into the invoking list, in the appropriate position
void merge(List, List); // merges the two lists l1 and l2 into the invoking list
void makeEmpty(); // re-initializes an exisiting list to be empty
friend ostream& operator<<(ostream& out, List& c); // friend function for class
private:
struct Node
{
int data;
Node *next;
};
Node *first;
Node* get_node(const int& entry, Node* link); // allocates, initializes, and returns the address of a new node
};
ostream& operator << (ostream& out, const List& c)
{
List::Node *cursor;
out << " ";
for (cursor = c.first; cursor != NULL && cursor -> next != NULL; cursor = cursor -> next)
out << cursor -> data << ", ";
if (cursor != NULL)
out << cursor -> data;
out << " ";
return out;
}
Here is what my compiler outputs
301Project3test.cpp: In function 'std::ostream& operator<<(std::ostream&, const List&)':
301Project3test.cpp:166:11: error: 'struct List::Node' is private within this context
List::Node *cursor;
301Project3test.cpp:30:16: note: declared private here
struct Node
301Project3test.cpp:170:21: error: 'List::Node* List::first' is private within this context
for (cursor = c.first; cursor != NULL && cursor -> next != NULL; cursor = cursor -> next)
301Project3test.cpp:35:15: note: declared private here
Node *first;
| List declares its friend operator<< as taking a List&, but you are implementing the operator as taking a const List& instead, so you are actually implementing a different operator, not the friend operator that has access to the private List::Node type.
|
69,293,388 | 69,293,505 | How to make class compatible with std::span constructor that takes a range? | I'd like to be able to pass my custom container this std::span constructor:
template< class R >
explicit(extent != std::dynamic_extent)
constexpr span( R&& range );
What do I need to add to my custom class to make it satisfy the requirements to be able to pass it to the std::span constructor that receives a range?
For example, with std::vector we are able to do this:
std::vector<int> v = {1, 2, 3};
auto span = std::span{v};
I've already added these to my custom class:
Type* begin()
{
return m_Data;
}
Type* end()
{
return m_Data + m_Length;
}
const Type* data() const
{
return m_Data;
}
size_t size() const
{
return m_Length;
}
...which in turn allowed me to use range-based loops, and std::data(my_container) as well as std::size(my_container). What am I missing to make it so that I can also pass my container to the std::span constructor? Does it require to implement a more complex iterator?
| This is because your Container does not satisfy contiguous_range, which is defined as:
template<class T>
concept contiguous_range =
random_access_range<T> && contiguous_iterator<iterator_t<T>> &&
requires(T& t) {
{ ranges::data(t) } -> same_as<add_pointer_t<range_reference_t<T>>>;
};
In the requires clause, the return type of ranges::data(t) is const Type*, which is different from add_pointer_t<range_reference_t<T>> that is Type*.
The workaround is adding a non-const data() to your Container which return Type*:
Type* data() { return m_Data; }
|
69,293,479 | 69,294,064 | How to mutate variadic arguments of a template | I'm trying to create a struct of arrays:
auto x = MakeMegaContainer<StructA, StructB, StructC>();
Which I want to, at compile time, produce a structure like:
struct MegaContainer {
std::tuple< Container<StructA>, Container<StructB>, Container<StructC> > Data;
};
The creation method is non-negotiable, and I think tuples are the best way to go, as later I could access one container's struct elements with std::get<StructA>(x)[index], if my container allows [].
I tried doing something like:
template<typename... LilStructs>
class StructStorage {
public:
template<typename OneStruct>
OneStruct& GetStruct(const uint64_t& id) {
return std::get<OneStruct>(m_Storage).Get(id); // Get is defined for MyContainer
}
template<typename OneStruct>
bool ContainsStruct(const uint64_t& id) {
return std::get<OneStruct>(m_Storage).Contains(id); // Contains is defined for MyContainer
}
private:
std::tuple<MyContainer<LilStructs>...> m_Storage;
};
But I don't think this works. I'm not sure how to take the variadic arguments and "wrap" them with a container
What should I do instead?
Follow up question: The MyContainer also takes additional arguments that customise it, like a max size. Is there a nice way of passing that, something like template<typename... LilStructs, uint64_t MAX_SIZE=4096>?
Here's a stripped down version of the container for a minimal reproducible example:
template<typename T_elem, typename T_int = uint64_t, T_int MAX_SIZE = 4096>
class MyContainer{
public:
MyContainer() = default;
~MyContainer() = default;
bool Contains(const T_int& id) const;
T_elem& operator[](const T_int& id);
T_elem& Get(const T_int& id);
private:
std::map<T_int, T_elem> m_Map;
T_int m_Size = 0;
};
template<typename T_elem, typename T_int, T_int MAX_SIZE>
bool MyContainer<T_elem, T_int, MAX_SIZE>::Contains(
const T_int& id
) const {
return m_Map[id] < m_Size;
}
template<typename T_elem, typename T_int, T_int MAX_SIZE>
T_elem& MyContainer<T_elem, T_int, MAX_SIZE>::operator[](const T_int& id) {
return m_Map[id];
}
template<typename T_elem, typename T_int, T_int MAX_SIZE>
T_elem& MyContainer<T_elem, T_int, MAX_SIZE>::Get(const T_int& id) {
return operator[](id);
}
When I try to compile:
void Test() {
struct SA { int x; };
struct SB { float x; };
struct SC { char x; };
auto& tests = StructStorage <SA, SB, SC>();
bool x = !tests.ContainsStruct<SA>(5);
}
I get the error:
c:\...\test.h(18): error C2039: 'Contains': is not a member of 'Trial::SA'
As I said, I know the error is in the std::tuple<MyContainer<LilStructs>...> m_Storage; line, and the error is indpendent of the implementation of MyContainer (provided that Contains and Get are implemented), but I do not know what to replace it with, or how to achieve the functionality I'm looking for (which was already described).
| Look at this part:
template <typename OneStruct>
OneStruct& GetStruct(const uint64_t& id) {
return std::get<OneStruct>(m_Storage).Get(id); // Get is defined for MyContainer
}
template <typename OneStruct>
bool ContainsStruct(const uint64_t& id) {
return std::get<OneStruct>(m_Storage).Contains(id); // Contains is defined for MyContainer
}
The m_Storage tuple is a tuple of MyContainer<LilStructs>...s and not LilStructs...s so what you actually want to do is this:
template <typename OneStruct>
OneStruct& GetStruct(const uint64_t& id) {
return std::get<MyContainer<OneStruct>>(m_Storage).Get(id); // Get is defined for MyContainer
// ^^^^^^^^^^^^^^^^^^^^^^
}
template <typename OneStruct>
bool ContainsStruct(const uint64_t& id) {
return std::get<MyContainer<OneStruct>>(m_Storage).Contains(id); // Contains is defined for MyContainer
// ^^^^^^^^^^^^^^^^^^^^^^
}
Also, your Contains() function is wrong. Use this:
template <typename T_elem, typename T_int, T_int MAX_SIZE>
bool MyContainer<T_elem, T_int, MAX_SIZE>::Contains(const T_int& id) const {
return m_Map.find(id) != m_Map.end();
}
Full working code:
#include <cstdint>
#include <cassert>
#include <tuple>
#include <map>
template <typename T_elem, typename T_int = uint64_t, T_int MAX_SIZE = 4096>
class MyContainer{
public:
MyContainer() = default;
~MyContainer() = default;
bool Contains(const T_int& id) const;
T_elem& operator[](const T_int& id);
T_elem& Get(const T_int& id);
private:
std::map<T_int, T_elem> m_Map;
T_int m_Size = 0;
};
template <typename T_elem, typename T_int, T_int MAX_SIZE>
bool MyContainer<T_elem, T_int, MAX_SIZE>::Contains(const T_int& id) const {
return m_Map.find(id) != m_Map.end();
}
template <typename T_elem, typename T_int, T_int MAX_SIZE>
T_elem& MyContainer<T_elem, T_int, MAX_SIZE>::operator[](const T_int& id) {
return m_Map[id];
}
template <typename T_elem, typename T_int, T_int MAX_SIZE>
T_elem& MyContainer<T_elem, T_int, MAX_SIZE>::Get(const T_int& id) {
return operator[](id);
}
template <typename ...LilStructs>
class StructStorage {
public:
template <typename OneStruct>
OneStruct& GetStruct(const uint64_t& id) {
return std::get<MyContainer<OneStruct>>(m_Storage).Get(id);
}
template <typename OneStruct>
bool ContainsStruct(const uint64_t& id) {
return std::get<MyContainer<OneStruct>>(m_Storage).Contains(id);
}
private:
std::tuple<MyContainer<LilStructs>...> m_Storage;
};
int main() {
struct SA { int x; };
struct SB { float x; };
struct SC { char x; };
auto tests = StructStorage<SA, SB, SC>();
assert(!tests.ContainsStruct<SA>(5));
}
Demo
|
69,293,663 | 69,293,945 | Parallel Arrays in C++ | Trying to create a program that takes a coffee flavor add-in and checks if it's valid using an array.
If valid it uses the array index to gather price information.
I managed to write the code below, but it only works for 1 iteration.
How can alter it so a user can enter: Cream and cinnamon and output the total of each add-in as well as the total price of the cup of coffee? The cup of coffee starts with a base price of $2.00
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declare variables.
string addIn; // Add-in ordered
const int NUM_ITEMS = 5; // Named constant
// Initialized array of add-ins
string addIns[] = { "Cream", "Cinnamon", "Chocolate", "Amaretto", "Whiskey" };
// Initialized array of add-in prices
double addInPrices[] = { .89, .25, .59, 1.50, 1.75 };
bool foundIt = false; // Flag variable
int x; // Loop control variable
double orderTotal = 2.00; // All orders start with a 2.00 charge
string QUIT = "XXX";
// Get user input
cout << "Enter coffee add-in or XXX to quit: ";
cin >> addIn;
// Write the rest of the program here.
for (x = 0; x < NUM_ITEMS && foundIt == false && addIn != QUIT; x++) {
if (addIn == addIns[x]) {
foundIt = true;
x--;
}
}
if (foundIt == true) {
cout << addIns[x] << " $" << addInPrices[x] <<endl;
cout << "$" << orderTotal + addInPrices[x] <<endl;
}
else {
cout << "Sorry, we do not carry that." <<endl;
cout << "Order total is $ " << orderTotal <<endl;
}
return 0;
}
| Your program is written to get a single output. For multiple outputs there have to be loops and the not found condition also has to be re-written.
try this
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declare variables.
const int NUM_ITEMS = 5; // Named constant
string addIn[NUM_ITEMS]; // Add-in ordered
// Initialized array of add-ins
string addIns[] = { "Cream", "Cinnamon", "Chocolate", "Amaretto", "Whiskey" };
// Initialized array of add-in prices
double addInPrices[] = { .89, .25, .59, 1.50, 1.75 };
//bool foundIt = false; // Flag variable
int x, i, j; // Loop control variable
double orderTotal = 2.00; // All orders start with a 2.00 charge
string QUIT = "XXX";
// Get user input
cout << "Enter coffee add-ins followed by XXX to quit: ";
for(i=0; i<NUM_ITEMS; i++) {
cin >> addIn[i];
if(addIn[i] == QUIT) {
i++;
break;
}
}
int foundIt[i];
// Write the rest of the program here.
for(j=0; j<i; j++) {
foundIt[j] = -1;
for(x = 0; x<NUM_ITEMS && foundIt[j] == -1 && addIn[j] != QUIT; x++) {
if (addIn[j] == addIns[x]) {
foundIt[j] = x;
}
}
}
for(j=0; j<i-1; j++) {
cout << addIn[j];
if(foundIt[j] != -1) {
cout << " $" << addInPrices[foundIt[j]] << endl;
orderTotal = orderTotal + addInPrices[foundIt[j]];
}
else {
cout << " - Sorry, we do not carry that." <<endl;
}
}
cout << "$" << orderTotal <<endl;
return 0;
}
Sample Outputs
Enter coffee add-ins followed by XXX to quit: Cream Cinnamon XXX
Cream $0.89
Cinnamon $0.25
$3.14
Enter coffee add-ins followed by XXX to quit: Cream Onion XXX
Cream $0.89
Onion - Sorry, we do not carry that.
$2.89
What I did was made addIn array of srings with NUM_ITEMS size instead of variable. Also, foundIt was made an integer array to keep track of indexes where the items are found in addIns array and -1 if not found.
To only access the items that user has entered in addIn, your QUIT has been made the termination condition in that array.
|
69,293,806 | 69,293,886 | How to show only the last value of a for loop? | I'm working on building a loop right now that only shows the end value. However, the code is showing all the integers though.
Here's my code:
#include <iostream>
using namespace std;
int sum = 0;
void findMultiples(int n){
cout <<"Enter a positive integer:"<<endl;
for(int i = 0; i <= n; i++)
if (i % 3 == 0)
cout << "Sum: "<<(sum =sum+i)<<endl;
}
int main() {
int num;
cin>>num;
findMultiples(num);
return 0;
}
| You are using for then if then showing output. The for and if scope area is one line without { }, so you are printing and summing at the same time and it is each time in the scope of if statement.
#include<iostream>
using namespace std;
int sum = 0;
void findMultiples(int n){
cout <<"Enter a positive integer:"<<endl;
for(int i = 0; i <= n; i++)
if (i % 3 == 0)
sum =sum+i;
cout << "Sum: "<<sum<<endl;
}
int main() {
int num;
cin>>num;
findMultiples(num);
return 0;
}
|
69,294,365 | 69,294,563 | How does one tell Windows 10 to tile, center, or stretch desktop wallpaper using WIN32 C/C++ API? | Goal: using C++, the Win32 SDK and Visual Studio 2019 to set the desktop wallpaper to be centered or tiled or stretched.
One can use SystemParametersInfo() to change the wallpaper. No problem at all.
Problem is telling the system to tile or center or stretch the wallpaper image.
Reading on the web, whether the wallpaper image is centered, tiled or stretched depends on a pair of registry entries:
HKCU\Control Panel\Desktop\TileWallpaper
HKCU\Control Panel\Desktop\WallpaperStyle
MS' WIN32 docs tell how to change the image but I can't find anything describing how to change the layout.
I have the following code. It is a console app project, the functions ripped out of my larger MFC app, thus the function names. This project's character set is set to Unicode, thus my use of W functions.
It does change the wallpaper image, but the wallpaper is always tiled, regardless of which of the onWallpaper___() functions are called.
Windows seems to completely ignore the registry changes. I have verified that my code does indeed change the registry entries' values.
Question: How does one tell Windows 10 to tile, center, or stretch desktop wallpaper using WIN32 C/C++ API?
Question: Are there different registry entries that should be used?
#include <Windows.h>
#include <iostream>
#include <string>
#include <cassert>
const int CENTERED = 0;
const int TILED = 1;
const int STRETCHED = 2;
void set_wallpaper_registry_keys(int discriminant) {
BOOL rtn;
HKEY hKey;
DWORD TileWallpaper = 0;
DWORD WallpaperStyle = 0;
switch (discriminant) {
case CENTERED: {
TileWallpaper = 0;
WallpaperStyle = 1; // some sources say use 6, makes no difference.
}
break;
case TILED: {
TileWallpaper = 1;
WallpaperStyle = 0;
}
break;
case STRETCHED: {
TileWallpaper = 0;
WallpaperStyle = 2;
}
break;
default: {
assert(false);
}
break;
}
std::wstring key_name(L"Control Panel\\Desktop");
rtn = RegOpenKeyEx(HKEY_CURRENT_USER, key_name.c_str(), 0, KEY_ALL_ACCESS, &hKey);
assert(rtn == ERROR_SUCCESS);
rtn = RegSetValueEx(hKey, L"TileWallpaper", 0, REG_DWORD, (BYTE *)&TileWallpaper, sizeof(DWORD));
assert(rtn == ERROR_SUCCESS);
rtn = RegSetValueEx(hKey, L"WallpaperStyle", 0, REG_DWORD, (BYTE *)&WallpaperStyle, sizeof(DWORD));
assert(rtn == ERROR_SUCCESS);
rtn = RegFlushKey(hKey);
assert(rtn == ERROR_SUCCESS);
rtn = RegCloseKey(hKey);
assert(rtn == ERROR_SUCCESS);
}
void OnWallpaperCentered() {
BOOL rtn;
set_wallpaper_registry_keys(CENTERED);
// set current image as wallpaper: SPI_SETDESKWALLPAPER
std::wstring fn = L"c:\\tmp\\stars.jpg";
rtn = SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (void *) (fn.c_str()), SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
assert(rtn == TRUE);
}
void OnWallpaperTiled() {
// TODO: Add your command handler code here
BOOL rtn;
set_wallpaper_registry_keys(TILED);
std::wstring fn = L"c:\\tmp\\snail.jpg";
rtn = SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (void *) (fn.c_str()), SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
assert(rtn == TRUE);
}
void OnWallpaperStretched() {
// TODO: Add your command handler code here
BOOL rtn;
set_wallpaper_registry_keys(STRETCHED);
std::wstring fn = L"c:\\tmp\\civ4.jpg";
rtn = SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (void*) (fn.c_str()), SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
assert(rtn == TRUE);
}
int main() {
//OnWallpaperTiled(); // Tiles the wallpaper
OnWallpaperCentered(); // Tiles the wallpaper as well
//OnWallpaperStretched(); // Tiles the wallpaper too
std::cout << "Hello World!\n";
}
| Try IDesktopWallpaper interface and IActiveDesktop interfaces.
Create objects for them by creating CLSID_DesktopWallpaper and CLSID_ActiveDesktopobjects.
|
69,294,684 | 69,294,882 | How to add the last element into a vector of a struct containing an array in c++ | Hi I want to add last element into a vector of struct containing an array. I have tried to add it under its loop but has issues with constant char. It says "invalid conversion from ‘const char*’ to char" [-fpermissive]
This my file named as myfile.txt.log
id value
1 ABC
2 BDV
3 COO
4 DDC
5 EEE
6 FGE
7 GTW
8 HFE
9 IOO
10 KPP
Desired output:
vector size: 11
vector content: ABC
vector content: BDV
vector content: COO
vector content: DDC
vector content: EEE
vector content: FGE
vector content: GTW
vector content: HFE
vector content: IOO
vector content: KPP
vector content: XXX
Here is my code. Any inputs will be great! I am on C++ 98
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
struct V {
char a[10];
};
int main() {
FILE * pFile;
char mystring [100];
int i;
char str[3];
char strCp[3];
vector<V> input;
pFile = fopen ("/uploads/myfile.txt.log" , "r");
if (pFile == NULL) perror ("Error opening file");
else {
while ( fgets (mystring , 100 , pFile) != NULL )
{
sscanf(mystring, "%d %s", &i, str);
strncpy(strCp, str, 3);
//puts(strCp);
V v;
int size = sizeof(strCp)/sizeof(strCp[0]);
for ( unsigned int a = 0; a < size; a++ )
{
v.a[a] = strCp[a];
v.a[a-1] = "XXX";
}
// Set vector
input.push_back(v);
}
//Vector Output
cout << "vector size: " << input.size() << endl;
vector<V>::iterator it;
for ( it = input.begin(); it != input.end(); it++ )
{
cout << "vector content: " << it->a << endl;
}
fclose (pFile);
}
return 0;
}
| Consider this using more C++ semantics than C:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
struct V {
char a[10];
};
int main()
{
std::vector<V> input;
std::string s;
int count = 0;
while (std::cin >> s)
{
count++;
if ((count % 2) == 0)
{
V v = {};
strncpy(v.a, s.c_str(), 4);
input.push_back(v);
}
}
V endV = {};
strncpy(endV.a, "XXX", 4);
input.push_back(endV);
fstream logfile;
logfile.open("logfile.txt", std::ios_base::out);
if (logfile.is_open())
{
for (size_t i = 0; i < input.size(); i++)
{
logfile << input[i].a << "\n";
}
logfile.close();
}
return 0;
}
|
69,295,305 | 69,295,402 | Constant time `contains` for `std::vector`? | I am working with some code that checks if std::vector contains a given element in constant time by comparing its address to those describing the extent of the vector's data. However I suspect that, although it works, it relies on undefined behaviour. If the element is not contained by the vector then the pointer comparisons are not permitted.
bool contains(const std::vector<T>& v, const T& a) {
return (v.data() <= &a) && (&a < v.data() + v.size());
}
Am I right in believing it is undefined behaviour? If so, is there any way to do the same thing without drastically changing the time complexity of the code?
| You can use std::less
A specialization of std::less for any pointer type yields the implementation-defined strict total order, even if the built-in < operator does not.
Update:
The standard doesn't guarantee that this will actually work for contains though. If you have say two vectors a and b, the total order is permitted to be &a[0], &b[0], &a[1], &b[1], &a[2], &b[2], ..., i.e., with the elements interleaved.
As pointed out in the comments, the standard only guarantees that std::less yields the implementation-defined strict total order, which is is consistent with the partial order imposed by the builtin operators. However, the standard doesn't guarantee the order of pointers pointing to different objects or arrays. Releated: https://devblogs.microsoft.com/oldnewthing/20170927-00/?p=97095
One interesting thing is that there's a similar usage in Herb Sutter's gcpp library(link). There's a comment saying that it is portable, the library is experimental though.
// Return whether p points into this page's storage and is allocated.
//
inline
bool gpage::contains(gsl::not_null<const byte*> p) const noexcept {
// Use std::less<> to compare (possibly unrelated) pointers portably
auto const cmp = std::less<>{};
auto const ext = extent();
return !cmp(p, ext.data()) && cmp(p, ext.data() + ext.size());
}
|
69,295,333 | 69,297,901 | Extract one colour channel from 4-dimensional cv::Mat | I'm working with OpenCV for a while and experiment with the DNN extension. My model has the input shape [1, 3, 224, 244] with pixel-depth uint8. So I put my m_inputImg which has 3-channels and 8 bit pixel depth in the function:
cv::dnn::blobFromImage(m_inputImg, m_inputImgTensor, 1.0, cv::Size(), cv::Scalar(), false, false, CV_8U);
Now I'm interested in having a Idea how my input image "lay" inside the cv::Mat tensor. Theoretically I know how the tensor looks like, but I don't understand how OpenCV do it. So to understand this I want to extract one colour channel. I've tried this:
cv::Mat blueImg = cv::Mat(cp->getModelConfigs().model[0].input.height,
cp->getModelConfigs().model[0].input.width,
CV_8UC3,
blob.ptr<uint8_t>(0, 0);
But what I get is something like that (see picture). I'm realy confused about that, can anybody help or has a good advice?
Thanks
| cv::Size() will use the original image size. You are interpreting the data wrong. Here are 4 ways to interpret a 512x512 (cv::Size()) loaded blob-start from the lenna image:
input (512x512):
blob-start as a 512x512 single channel image:
blob-start as a 512x512 BGR image:
blob-start as a 224x224 BGR image:
blob-start as a 224x224 single channel:
here's the code:
int main()
{
cv::Mat img = cv::imread("C:/data/Lenna.png"); // 8UC3
cv::imshow("img", img);
cv::Mat blob;
cv::dnn::blobFromImage(img, blob, 1.0, cv::Size(), cv::Scalar(), false, false, CV_8U);
cv::Mat redImg = cv::Mat(img.rows,
img.cols,
CV_8UC1,
blob.ptr<uint8_t>(0, 0));
cv::imshow("blob 1", redImg);
cv::imwrite("red1.jpg", redImg);
cv::Mat redImg3C = cv::Mat(img.rows,
img.cols,
CV_8UC3,
blob.ptr<uint8_t>(0, 0));
cv::imshow("redImg3C", redImg3C);
cv::imwrite("red3C.jpg", redImg3C);
cv::Mat redImg224_3C = cv::Mat(224,
224,
CV_8UC3,
blob.ptr<uint8_t>(0, 0));
cv::imshow("redImg224_3C", redImg224_3C);
cv::imwrite("redImg224_3C.jpg", redImg224_3C);
cv::Mat redImg224_1C = cv::Mat(224,
224,
CV_8UC1,
blob.ptr<uint8_t>(0, 0));
cv::imshow("redImg224_1C", redImg224_1C);
cv::imwrite("redImg224_1C.jpg", redImg224_1C);
cv::waitKey(0);
}
Imho you have to do in your code:
cv::dnn::blobFromImage(m_inputImg, blob, 1.0, cv::Size(), cv::Scalar(), false, false, CV_8U);
cv::Mat blueImg = cv::Mat(m_inputImg.rows,
m_inputImg.cols,
CV_8UC3,
blob.ptr<uint8_t>(0, 0);
OR
cv::dnn::blobFromImage(m_inputImg, blob, 1.0, cv::Size(cp->getModelConfigs().model[0].input.width , cp->getModelConfigs().model[0].input.height), cv::Scalar(), false, false, CV_8U);
cv::Mat blueImg = cv::Mat(cp->getModelConfigs().model[0].input.height,
cp->getModelConfigs().model[0].input.width,
CV_8UC3,
blob.ptr<uint8_t>(0, 0);
In addition, here's the version of setting the spatial blob image size to a fixed size (e.g. the desired DNN input size):
cv::Mat blob2;
cv::dnn::blobFromImage(img, blob2, 1.0, cv::Size(224,224), cv::Scalar(), false, false, CV_8U);
cv::Mat blueImg224_1C = cv::Mat(224,
224,
CV_8UC1,
blob2.ptr<uint8_t>(0, 0));
cv::imshow("blueImg224_1C", blueImg224_1C);
cv::imwrite("blueImg224_1C.jpg", blueImg224_1C);
Giving this image:
|
69,295,821 | 69,297,083 | Strange behavior using CString in swscanf directly | I have one problem with CString and STL's set.
It looks a bit strange to use CString and STL together, but I tried to be curious.
My code is below:
#include "stdafx.h"
#include <iostream>
#include <set>
#include <atlstr.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t line[1024] = {0};
FILE * pFile = _wfopen(L"F:\\test.txt", L"rt");
set<CString> cstr_set;
while (fgetws(line, 1024, pFile))
{
CString cstr;
swscanf(line, L"%s\n", cstr);
cstr_set.insert(cstr);
}
fclose(pFile);
cout << "count" << cstr_set.size();
return 0;
}
The contents of the test.txt is:
13245
123
2344
45
After the loop ends, cstr_set contains only one value.
It works as if cstr is static or const variable.
What is the problem?
| A CString is a Microsoft implementation wrapping a character array into a C++ object to allow simpler processing.
But, swscanf is a good old C function that knows nothing about what a CString is: it just expects its arguments to be large enough to accept the decoded values. It should never be directly passed a CString.
The correct way would be:
...
#include <cstring>
...
while (fgetws(line, 1024, pFile))
{
line[wcscspn(line, L"\n")] = 0; // remove an optional end of line
CString cstr(line);
cstr_set.insert(cstr);
}
...
|
69,295,846 | 69,295,913 | How to align a structure correctly? | I am trying to align a structure using the directive (#pragma pack).
I need it has 112 bytes in size. (14*8=112 bytes).
However it has 80 bytes only.
How to do it correctly?
#pragma pack (8)
struct Deal
{
long deal_ticket;
long order_ticket;
long position_ticket;
long time;
long type;
long entry;
char symbol[8];
double volume;
double price;
double profit;
double swap;
double commission;
long magic;
long reason;
};
int main()
{
cout << sizeof(Deal) << endl;
}
Thank you so much!!
|
I need it has 112 bytes in size. (14*8=112 bytes).
long is only guaranteed to be at least 32 bits which is 4 bytes (assuming 8 bit byte); not 8 bytes.
If you want each integer to be 64 bits, then you can use std::int64_t instead of long.
#pragma pack never increases the size of a class. It only ever decreases the size by removing padding that is otherwise required for alignment.
P.S. #pragma pack doesn't exist in standard C++ (in fact, no standard pragmas exist in C++). It is a language extension.
|
69,296,446 | 69,296,547 | Calling function twice gives segfault (in connection with char* to string conversion) | I want to expand a string ("%LOCALAPPDATA%/test.txt") with a Windows environment path. The following function in principle does the job, but calling it again with the same output string (or assigning some value to the output string before calling the function) gives a segfault.
Obviously I am making some (probably really bad) mistake by converting char* to std::string, but I don't really understand what is going on here (beside the fact that some memory address is not available later on).
#include "processenv.h"
void expandWindowsString(const std::string &input, std::string &output)
{
const char* in = input.c_str();
char* out;
ExpandEnvironmentStrings(in, out, 1024);
output = out;
}
int main(int argc, char *argv[])
{
std::string path;
expandWindowsString("%LOCALAPPDATA%/test.txt", path);
std::cout << "path is " << path << std::endl;
//works fine so far, but if I execute the function again (with 'path') or initialising path beforehand with std::string path = "", a segfault occurs.
expandWindowsString("%LOCALAPPDATA%/test.txt", path); // commenting out this line, makes the code work.
std::cout << "path is " << path << "\n";
}
| As the documentation explains:
lpDst
A pointer to a buffer that receives the result of expanding the environment variable strings in the lpSrc buffer.
The buffer needs to be supplied by the caller, while the code simply passes an uninitialized pointer, alongside tricking the system into believing that it points at memory with a size of 1024 bytes.
A simple fix would be:
void expandWindowsString(const std::string &input, std::string &output)
{
const char* in = input.c_str();
char out[1024];
ExpandEnvironmentStrings(in, out, 1024);
output = out;
}
There's lots of room for improvement, e.g.
Using the Unicode version
Handling errors (as explained in the documentation)
Repeatedly growing the output buffer in case the API call returns a value larger than the provided buffer length
Constructing a std::string using the pointer and length
Returning a value rather than using an out parameter
As for why it fails when being called a second time: That's a meaningless question. The code exhibits undefined behavior by writing through an uninitialized pointer. With that, any outcome is possible, including the code appearing to work as expected.
|
69,296,888 | 69,296,969 | Why decltype(auto) infers T& as return type, while dedicated T& does not? | Consider this snippet:
#include <stdexcept>
template <typename T> class MyClass;
template <typename T> struct MyClass<T &> {
constexpr T &foo() && {
return value != nullptr ? std::move(*value)
: throw std::runtime_error("foo");
}
constexpr decltype(auto) bar() && {
return value != nullptr ? std::move(*value)
: throw std::runtime_error("bar");
}
T *value;
};
int main() {
const int &good = MyClass<int &>{}.bar();
const int &bad = MyClass<int &>{}.foo();
}
Demo
Why is return specification decltype(auto) in method bar working, while T& in foo does not?
|
Why decltype(auto) infers T& as return type
No, the return type of bar() is T&&, i.e. int&& in this case. For decltype:
if the value category of expression is xvalue, then decltype yields T&&;
std::move(*value) is an xvalue-expression, so the deduced return type is T&&.
On the other hand, the return type of foo is specified as T&, but std::move(*value) is an xvalue (rvalue) and can't be bound to T&, i.e. an lvalue-reference to non-const.
|
69,297,501 | 69,298,431 | C++ placement new alignment of classes (on a SAMD21 microcontroller) | I am working on an application which is running on a SAMD21 microcontroller. For those unfamiliar with the SAMD21, it contains an ARM Cortex-M0+ processor. The specific model I am using has 32 kB of RAM. My application is running up to the limits of that 32 kB, so I've been working on optimizing the code for memory usage.
One optimization I've been working on is reducing heap fragmentation. For example, I may have a scenario such as the following:
A *my_obj = new A();
B *my_second_obj = new B();
delete A;
C *my_third_obj = new C();
In the above example, when instantiating my_third_obj, the memory allocator may attempt to place it in the empty location that was initially being used by my_obj. However, if my_third_obj doesn't fit in that spot, then the memory allocator will simply allocate some more space at the top of the heap and move the heap pointer. This will leave a "hole" where my_obj was located (which may be filled later by other objects), but this creates heap fragmentation.
In my specific application, I've determined that I will ever only need one active instance of classes A, B, or C at any point in time. Because of this, I was thinking about creating a block of memory which holds the current instance of any of those classes, and simply making the memory block as big as the largest class so that it can hold any of the classes. This would reduce heap fragmentation since there would always be a specific place in memory where I would be allocating these specific classes.
Here's a simple example of what I am thinking:
uint32_t max_size = sizeof(A);
max_size = (sizeof(B) > max_size) ? sizeof(B) : max_size;
max_size = (sizeof(C) > max_size) ? sizeof(C) : max_size;
uint8_t *buffer = new uint8_t[max_size];
//Some time later in the program...
C *my_obj = new(buffer) C();
//Some time later in the program...
my_obj->~C();
my_obj = NULL;
memset(buffer, 0, sizeof(max_size));
B *my_other_obj = new(buffer) B();
I've never really used placement new in previous code that I've written, but I think it would be useful in my current circumstance. My main question here is: given the example that I've laid out, do I need to alter the code in any way to handle alignment issues? Classes A, B, and C all have different member variables and different sizes. Will this code just "work", or do I need to do anything special to handle memory alignment?
Thanks!
|
do I need to alter the code in any way to handle alignment issues?
Yes.
do I need to do anything special to handle memory alignment?
Yes.
uint8_t conceptually represents an unsigned integer with 8 bits. Use char or unsigned char to represent 1 byte.
Anyway, use operator new with size and alignment:
auto maxsize = max_of_3(sizeof(A), sizeof(B), sizeof(C)),
auto neededalign = std::align_val_t(max_of_3(alignof(A), alignof(B), alignof(C));
void *buffer = operator new(maxsize, neededalign);
or statically:
std::aligned_storage<
max_of_3(sizeof(A), sizeof(B), sizeof(C)),
max_of_3(alignof(A), alignof(B), alignof(C))> buffer;
A *stuff = new(buffer.data) A;
|
69,297,570 | 69,298,021 | Why is a pointer to pointer treated differently than a pointer in spite of corresponding corrections | I'm trying to delete a Node from a Doubly Linked List. The function deleteNode() will receive the head of the linked list and the node to be deleted. However, depending on whether I pass the node to be deleted as a pointer or a pointer to pointer, the code behaves differently (in spite of making the corresponding corrections in syntax).
Here is my structure for Doubly Linked List node -
struct DNode {
int val;
struct DNode* next;
struct DNode* prev;
DNode(int val) { //constructor
this->val = val;
next = NULL;
prev = NULL;
}
};
The following code works perfectly fine:
void deleteNode(struct DNode** head, struct DNode* deleteMe) {
//head is pointer to pointer, deleteMe is pointer
if(!(*head) || !deleteMe) {
cout<<"\nDeletion not possible";
return;
}
if(deleteMe->prev != NULL)
deleteMe->prev->next = deleteMe->next;
if(deleteMe->next != NULL)
deleteMe->next->prev = deleteMe->prev;
if(deleteMe == *head)
*head = deleteMe->next;
delete deleteMe;
}
Correspoding Driver Code -
/*at this point, I have pushed elements into the Linked List to make it 4->3->2->1, where 4 is
the head*/
deleteNode(&head, head);
deleteNode(&head, head->next);
deleteNode(&head, head->next);
However, when I send both parameters as pointer to pointer, I experience a crash at runtime:
void deleteNode(struct DNode** head, struct DNode** deleteMe) {
if(!(*head) || !(*deleteMe)) {
cout<<"\nDeletion not possible";
return;
}
if((*deleteMe)->prev != NULL)
(*deleteMe)->prev->next = (*deleteMe)->next;
if((*deleteMe)->next != NULL)
(*deleteMe)->next->prev = (*deleteMe)->prev;
if(*deleteMe == *head)
*head = (*deleteMe)->next;
delete *deleteMe;
}
Corresponding driver code:
/*at this point, I have pushed elements into the Linked List to make it 4->3->2->1, where 4 is
the head*/
deleteNode(&head, &head);
deleteNode(&head, &head->next);
deleteNode(&head, &head->next);
PS - this is not entirely an issue with delete:
if you comment the line delete *deleteMe in the erroneous code, the code will run but the output will be different.
Output for working code: 3
Output for erroneous code after commenting the delete line: 3->1
| Here, when you pass &head and &head,
if(*deleteMe == *head)
*head = (*deleteMe)->next;
*deleteMe and *head are the same object (the object whose address you passed in), and they are still the same object after the assignment.
(That is, it is equivalent to both *head = (*head)->next; and *deleteMe = (*deleteMe)->next.)
So this,
delete *deleteMe;
does the same as delete *head in this case, and then things go boom.
In the first case, *head and deleteMe are different objects, so assigning to *head does not affect deleteMe.
As an illustration, this is what happens ("main_head" is the variable in main).
When you enter the function, you have this situation:
head
|
v +---+ +---+
main_head---->| ---->| ----> ...
^ +---+ +---+
| ^
deleteMe |
(*deleteMe)->next
And after the assignment *head = (*deleteMe)->next:
head +-------------+
| | |
| | v
v | +---+ +---+
main_head-+ | ---->| ----> ...
^ +---+ +---+
|
deleteMe
And you can see that head and deleteMe still point to main's head, and that is the object you assigned a value to.
With the working code, you start with this:
head
|
v +---+ +---+
main_head---->| ---->| ----> ...
+---+ +---+
^ ^
| |
deleteMe deleteMe->next
And end up with
head +-------------+
| | |
| | v
v | +---+ +---+
main_head-+ | ---->| ----> ...
+---+ +---+
^ ^
| |
deleteMe deleteMe->next
|
69,297,852 | 69,297,933 | std::initializer_list as right hand argument for overloaded operator? | I want to use something like the "in" operator available in other programming languages. I read many posts about that already. But, nothing that fits my needs.
What I wanted to do is a little bit different. Please see the following first example:
#include <iostream>
#include <initializer_list>
#include <algorithm>
bool operator ==(const int lhs, std::initializer_list<int>& il) {
return std::find(il.begin(), il.end(), lhs) != il.end();
}
int main() {
std::initializer_list<int> il{1,2,3,4,5};
std::cout << (3 == il) << '\n';
// std::cout << (3 == {1,2,3,4,5}) << '\n'; // Does not compile
}
But this does not compile. Presumably, because an initalizer list is no expression. Although there are exceptions. A std::initializer_list maybe a function parameter, although also here expressions are expected.
And since any operator is basically also a function, my hope was, that I also can use std::initalizer_list as argument.
But I cannot.
I tried the same approach by defining an own operator with a name by misusing overloading of 2 operators. See below:
#include <iostream>
#include <vector>
// New operator: is_in
enum { is_in };
int operator < (const int& lhs, decltype(is_in)) { return lhs; }
int operator > (int lhs, std::vector<int>& rhs) { return std::find(rhs.begin(), rhs.end(), lhs) != rhs.end();}
int operator > (int lhs, std::initializer_list<int>& rhs) { return std::find(rhs.begin(), rhs.end(), lhs) != rhs.end(); }
int main() {
std::vector validValues{ 1, 2, 3, 4, 5 };
bool b = (5 <is_in> validValues);
// bool b = (5 <is_in> { 1, 2, 3, 4, 5 }); // Does not compile
std::cout << b << '\n';
}
Same principle, same problem . . .
Is there any way to make this happen?
| You need to take the initializer_list by const&:
bool operator==(const int lhs, const std::initializer_list<int>& il)
std::cout << (3 == std::initializer_list{1,2,3,4,5}) << '\n';
For the is_in test you could overload the comma operator and do something like this:
template<class T>
struct is_in {
is_in(const std::initializer_list<T>& il) : ref(il) {}
const std::initializer_list<T>& ref;
};
template<class T>
bool operator,(const T& lhs, const is_in<T>& rhs) {
return std::find(rhs.ref.begin(), rhs.ref.end(), lhs) != rhs.ref.end();
}
int main() {
bool b = (5, is_in{ 1, 2, 3, 4, 5 });
std::cout << b << '\n';
}
|
69,297,978 | 69,304,522 | Implicit conversion sequence from {} in a copy-initialization context for a type with an explicit default constructor | (Consider this question for C++17 and forward)
LWG issue 3562(+), whether nullopt_t's requirement to not be DefaultConstructible could be superseded with the explicit explicitly-defaulted default-constructor of other tag types:
struct nullopt_t { explicit nullopt_t() = default; };
was closed as not a defect (NAD), with the following rationale
2021-06-14 Reflector poll:
Current wording prevents an implicit conversion sequence from {}.
(+) Note that this issue mentions both LWG issue 2510 and CWG issues 1518 and 1630, whose resolutions (changed/superseded) were tightly coupled.
Consider the following example:
struct my_nullopt_t {
explicit constexpr my_nullopt_t() = default;
};
struct S {
constexpr S() {} // user-provided: S is not an aggregate
constexpr S(S const&) = default;
S& operator=(S const&) = default; // #1
S& operator=(my_nullopt_t) = delete; // #2
};
int main() {
S s{};
s = {}; // #3
}
which I would expect is well-formed as the overload #2 is not viable for the assignment at #3, as the default constructor of my_nullopt_t is explicit (meaning my_nullopt_t is moreover not an aggregate in C++17). I particularly thought this was governed by [over.match.ctor]/1:
When objects of class type are direct-initialized, copy-initialized from an expression of the same or a derived class type ([dcl.init]), or default-initialized, overload resolution selects the constructor. For direct-initialization or default-initialization that is not in the context of copy-initialization, the candidate functions are all the constructors of the class of the object being initialized. For copy-initialization (including default initialization in the context of copy-initialization), the candidate functions are all the converting constructors ([class.conv.ctor]) of that class. [...]
[class.conv.ctor]/1 A constructor that is not explicit ([dcl.fct.spec]) specifies a conversion from the types of its parameters (if any) to the type of its class. Such a constructor is called a converting constructor.
But given the reflector's comment above I'm probably mistaken. Is possibly [over.match.list]/1
In copy-list-initialization, if an explicit constructor is chosen, the initialization is ill-formed. [ Note: This differs from other situations ([over.match.ctor], [over.match.copy]), where only converting constructors are considered for copy-initialization. This restriction only applies if this initialization is part of the final result of overload resolution. — end note ]
governing this case via entry from [over.ics.list]/7?
We may finally note that we also see compiler variance here, where Clang accepts the program whereas GCC rejects it (for C++11 through C++20) with an ambiguity error. GCC particularly seems to consider #2 a viable overload, whereas Clang does not.
GCC error: ambiguous overload for 'operator='
DEMO
Question
What standardese passages support's the reflector's rationale above, e.g. applied to the example above?
Is this then in support of GCC's rejection of the program above, such that Clang is wrong to accept it?
| GCC is right, and Clang and MSVC are wrong. This is highlighted in:
CWG1228: Copy-list-initialization and explicit constructors
which was also closed as NAD.
Somewhat surprisingly, the rules regarding explicit constructors differ between copy-list-initialization ([over.match.list]) and copy-initialization ([over.match.copy]) [emphasis mine]:
1228. Copy-list-initialization and explicit constructors
Section: 12.2.2.8 [over.match.list]
Status: NAD
Submitter: Daniel Krügler
Date: 2010-12-03
The rules for selecting candidate functions in
copy-list-initialization (12.2.2.8 [over.match.list]) differ from
those of regular copy-initialization (12.2.2.5 [over.match.copy]): the
latter specify that only the converting (non-explicit) constructors
are considered, while the former include all constructors but state
that the program is ill-formed if an explicit constructor is selected
by overload resolution. This is counterintuitive and can lead to
surprising results. For example, the call to the function object p
in the following example is ambiguous because the explicit constructor
is a candidate for the initialization of the operator's parameter:
struct MyList {
explicit MyStore(int initialCapacity);
};
struct MyInt {
MyInt(int i);
};
struct Printer {
void operator()(MyStore const& s);
void operator()(MyInt const& i);
};
void f() {
Printer p;
p({23});
}
Rationale (March, 2011):
The current rules are as intended.
|
69,298,110 | 69,298,264 | How do I read from cin until it is empty? | I am trying to read pairs of lines from a file passed in through the cin.
I need to read until the file is empty.
If one line of the pair is empty, I need to save that line as "".
If both lines are empty, then both need to be saved and processed as "".
I am using the getline to read the lines in, with a while-loop that keeps going until both lines are empty.
However, I need it to continue until the file is empty, as it is possible that 2 empty lines are followed by a number of filled lines.
This is how I have it at the moment:
getline(cin, str1); getline(cin, str2);
while (str1 == "" | str1 != "") {
....
str1 = ""; str2 = "";
getline(cin, str1); getline(cin, str2);
}
| If the file contains two line feeds in a row this would not work. You can use cin.eof() to check when you’ve reached the end of the file. If it returns 1 then you’ve attempted to read beyond the end of the file.
|
69,298,302 | 69,298,938 | Inlcude fftw3.h with cmake in a linux environment | I want to use fftw library.
In my cpp file I included as #include <fftw3.h>
I downloaded the library and I saved it in ./fftw
Then I typed:
cd fftw
./configure
make
make install
cd ..
In my project I am already using OpenCV, so my CMakeLists.txt is:
cmake_minimum_required(VERSION 2.8) # CMake version check
project( main )
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable( main main.cpp )
# set(CMAKE_BUILD_TYPE Debug)
target_link_libraries( main ${OpenCV_LIBS} )
target_link_libraries( main ./fftw)
Finally I execute cmake CMakeLists.txt but when I try to make my executable, it complains that fftw3.h: No such file or directory.
How could I make it work?
Thanks.
| You can also use ./configure --prefix /where/you/want/to/install to set the directory you want the library to be installed in then make sure that you run make install inside ./fftw directory.
You may need to use sudo make install depending on the path and permissions.
Change your CMakeLists.txt to include the following:
cmake_minimum_required(VERSION 2.8) # CMake version check
project( main )
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable( main main.cpp )
# set(CMAKE_BUILD_TYPE Debug)
target_link_libraries( main ${OpenCV_LIBS} )
target_link_libraries( main fftw3 )
Then execute cmake CMakeLists.txt and finally make
The above build's correctly on the following platform:
OS: Ubuntu Linux 21.04
Kernel: 5.11.0-34-generic
cmake Version: 3.18.4
g++: 10.3.0
Example main.cpp used:
#include <fftw3.h>
#define NUM_POINTS 64
#include <stdio.h>
#include <math.h>
#define REAL 0
#define IMAG 1
void acquire_from_somewhere(fftw_complex* signal) {
/* Generate two sine waves of different frequencies and
* amplitudes.
*/
int i;
for (i = 0; i < NUM_POINTS; ++i) {
double theta = (double)i / (double)NUM_POINTS * M_PI;
signal[i][REAL] = 1.0 * cos(10.0 * theta) +
0.5 * cos(25.0 * theta);
signal[i][IMAG] = 1.0 * sin(10.0 * theta) +
0.5 * sin(25.0 * theta);
}
}
void do_something_with(fftw_complex* result) {
int i;
for (i = 0; i < NUM_POINTS; ++i) {
double mag = sqrt(result[i][REAL] * result[i][REAL] +
result[i][IMAG] * result[i][IMAG]);
printf("%g\n", mag);
}
}
int main() {
fftw_complex signal[NUM_POINTS];
fftw_complex result[NUM_POINTS];
fftw_plan plan = fftw_plan_dft_1d(NUM_POINTS,
signal,
result,
FFTW_FORWARD,
FFTW_ESTIMATE);
acquire_from_somewhere(signal);
fftw_execute(plan);
do_something_with(result);
fftw_destroy_plan(plan);
return 0;
}
|
69,299,093 | 69,299,232 | Unexpected behaviour when using inheritance | I have a Base class, which is then inherited by Foo, and Foo is in turn inehrited by Bar.
Here is the header file base.h for my Base class:
#pragma once
class Base {
public:
void runExample();
private:
virtual void print();
};
And the implementation base.cpp:
#include "base.h"
void Base::runExample() {
print();
}
void Base::print() {};
Here is the header file foo.h for my Foo class:
#pragma once
#include "../base/base.h"
class Foo : public Base {
public:
Foo();
private:
void print();
const char* toPrint;
};
And the implementation foo.cpp:
#include "foo.h"
Foo::Foo() {
toPrint = "Hello Foo";
}
void Foo::print() {
std::cout << toPrint << std::endl;
}
Here is the header file bar.h for my Bar class:
#pragma once
#include "../foo/foo.h"
class Bar : public Foo {
public:
Bar();
private:
const char* toPrint; // "overrides" toPrint from parent class Foo?
};
And the implementation bar.cpp:
#include "bar.h"
Bar::Bar() {
toPrint = "Hello Bar";
}
And finally, my main function:
#include "../bar/bar.h"
int main() {
Bar bar = Bar();
bar.runExample();
}
So, I have this kind of relationship between the classes:
Bar is a Foo which is a Base.
What I was expecting to see in the output was "Hello Bar", but what I actually see is "Hello Foo".
If I "override" the print method declared in Foo in Bar to print toPrint then I get the expected result, however this seems to break the point of inheritance; i.e. why would I need to re-define the functionality when it's already defined.
What I am expecting is that when Bar.print() is invoked, it uses Foos implementation, but the actual field toPrint has been "replaced" with the value inside the Bar implementation.
I am very new to C++, and I'm coming from a Kotlin background. Forgive me if this is like C++ 101 basics, but I'm pretty confused as to why this is happening. Could anyone point me in the right direction?
| In C++, data members cannot be "overridden" as you expect, and a reference to toPrint will not be dynamically bound to equally named data members in subclasses.
With
class Bar : public Foo {
...
const char* toPrint; // "overrides" toPrint from parent class Foo?
};
you introduce a member variable Bar::toPrint next to Foo::toPrint, which is inherited. The code
void Foo::print() {
std::cout << toPrint << std::endl;
}
will always stick to the toPrint-member in his scope, i.e. to Foo::toPrint.
The following code illustrates this behaviour:
struct Base {
const char* toPrint = "Base";
virtual void print() const { cout << toPrint << std::endl; }
};
struct Derived: public Base {
const char* toPrint = "Derived";
void printBoth() const { cout << "own:" << toPrint << "; inherited: " << Base::toPrint << std::endl; }
};
int main() {
Derived d;
cout << "call inherited method print:" << std::endl;
d.print();
cout << "call method printBoth, showing both data members:" << std::endl;
d.printBoth();
}
Output:
call inherited method print:
Base
call method printBoth, showing both data members:
own:Derived; inherited: Base
|
69,299,142 | 69,299,573 | Why does std::inlcudes use the less than operator in the condition rather than the equality operator? | I have this implementation of the algorithm std::includes from https://en.cppreference.com/w/cpp/algorithm/includes
template<class InputIt1, class InputIt2>
bool includes(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2)
{
for (; first2 != last2; ++first1)
{
if (first1 == last1 || *first2 < *first1)
return false;
if ( !(*first1 < *first2) )
++first2;
}
return true;
}
It works just fine however I wonder why in the second if statement inside the loop uses less than operator < rather than equality operator ==?
Here is my similar implementation:
template<class InputIt1, class InputIt2>
bool including(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2){
while (first2 != last2){
if (first1 == last1 || *first2 < *first1)
return false;
if ( *first1 == *first2 )
++first2;
++first1;
}
return true;
}
int main(){
std::vector<int> v{1, 5, 7, 23, 24, 57, 77};
// std::sort(v.begin(), v.end());
int a[]{7, 24};
std::cout << including(v.begin(), v.end(), a, a + 2) << '\n'; // 1
std::cout << std::includes(v.begin(), v.end(), a, a + 2) << '\n'; // 1
}
So I've concluded this:
The first condition: *first2 < *first1 -> returns false.
The second condition: !(*first1 < *firs2) -> *first1 >= *first2
So *first1 > *first2 causes the algorithm return false and *first1 >= *first2 causes firsts2 be incremented so the only condition first2 gets incremented is when *first1 == *first2 So why using the less than < along with negation operator ! operators rather than using directly equals operator == like in my implementation?
Is that only for some sort of readability and compatibility sake?
Is my analysis correct? Thank you!
| The algorithm is working on a sorted range. You need a < relation to sort a range of elements, but not necessarily a == relation, hence using < poses less restrictions and is more generic.
Also consider that most algorithms and containers use < rather than == to compare elements. See for example std::map:
Everywhere the standard library uses the Compare requirements, uniqueness is determined by using the equivalence relation. In imprecise terms, two objects a and b are considered equivalent (not unique) if neither compares less than the other: !comp(a, b) && !comp(b, a).
Two keys in a map are considered equivalent (not equal!) when !comp(a,b) && !comp(b,a). Most of the time this is the same as a == b, but not necessarily.
|
69,299,277 | 69,299,431 | How do I input a quadratic equation in C++? | We were given an assignment to program the following, which I have been trying to figure out how to solve for the last 2 hours but to no avail.
How do you actually solve a complex formula having different operations in one mathematical expression?
For you to properly understand which of the operations are to be solved in order, try recreating the quadratic equation, ax^2 + bx + c, in C++ on your own!
Instructions:
The value of a, b, c, and x are already provided for you in the code editor. Remake the formula using C++'s math functions and operators and store it into one variable.
Print the value of the variable that stores the formula. To understand which to actually solve first in the equation, try tracing it out by yourself and manually solve it and see if your answer match that of the sample output.
Sample output: 16
TL;DR I am told to recreate the quadratic equation on my own using the given variables with their values.
Here is my current output which failed:
#include<iostream>
#include <cmath>
int main(void) {
int a = 2;
int b = 2;
int c = 4;
int x = 2;
// TODO:
// 1. Compute for the result of the quadratic equation
// using the variables provided above and the math library
double result;
result = (a * x + b * x) pow(2, 2) + c;
// 2. Print the output required by the output sample
std::cout << result;
return 0;
}
It prints out 4 when it should be 16.
| You use this code:
result = a * pow(x, 2) + b * x + c;
|
69,299,285 | 69,343,256 | Qt: Import Qml Module in imported Javascript resource | I like to access a registered QObject from within an imported js resource (qml -> .js -> Module).
Access from QML works, but using ".import" as explained in the docs from within the js file does not. Some related issues raise the impression it may work (another) or not.
Is it generally possible and how, only possible for certain modules, or not at all?
Code with the annotated output of the console outputs:
main.cpp
[...]
qmlRegisterSingletonInstance<MyModule>("org.example.MyModule", 1, 0, "MyModule", (new MyModule()));
[...]
MyModule.hpp
#pragma once
#include <QObject>
class MyModule : public QObject
{
Q_OBJECT
public:
enum SOMETHING { AAA, BBB, CCC, DDD, EEE, FFF };
Q_ENUM(SOMETHING)
};
main.qml
import org.example.MyModule 1.0
import "qrc:/something.js" as Something
[...]
console.log(MyModule, MyModule.DDD)// prints something like: "MyModule(0x....) 3"
[...]
Something.doit()
[...]
something.js
.import org.example.MyModule 1.0 as MyModule
[...]
console.log(MyModule, MyModule.DDD) // prints something like: "[object Object] undefined"
[...]
| Got an answer from support: Apparently, you need to prefix the Module with the import namespace, i.e. MyModule.MyModule.DDD instead of MyModule.DDD:
.import org.example.MyModule 1.0 as MyModule
[...]
console.log(MyModule.MyModule, MyModule.MyModule.DDD)
[...]
|
69,299,652 | 69,299,761 | Is it possible to use continue keyword outside a loop in C++? | According to ISO C++:
The continue statement shall occur only in an iteration-statement and
causes control to pass to the loop-continuation portion of the smallest
enclosing iteration-statement, that is, to the end of the loop. More
precisely, in each of the statements
while (foo) { do { for(;;){
{ { {
// ... //.... //...
} } }
contin:; contin:; contin:;
} } while (foo); }
a continue not contained in an enclosed iteration statement is
equivalent to goto contin
Based on the last part of the quote, I thought that the following would be allowed:
#include <iostream>
using namespace std;
int main() {
continue;
cout << "Will be jumped" << endl;
contin:
}
I thought this will work as a goto statement, jumping to contin. What did I miss?
| This is slight phrasing issue. What the quote means is that in
for (;;) {
{
// ...
}
contin: ;
}
The ... can be anything, including another iteration statement.
for (;;) {
{
while(foo()) {
// ...
continue;
}
}
contin: ;
}
The continue; that is not nested inside another looping construct, is going to be equivalent to goto contin;. But if it is contained, it will of course continue the internal loop, not the outer one.
Bear in mind that contin: ; is used for exposition purposes. It doesn't mean there's a literal C++-level label you can do things with.
|
69,299,663 | 69,300,216 | change the value inside the address using a patern? | I am a modder and I need to change the value of the object position. I inject into the game using my dll file. I have a pattern like this 9F4FF 0 C4 A8 70 39 41 and an address like this 0x7FF6CC7DCCD. I found this address & pattern using cheat engine and x64 Debug. I need to change the value at this address using this address or pattern, how can I do this in C++?
P.S. object = entity
| you can use function defined in window header ...
they are :
ReadProcessMemory ()
WriteProcessMemory ()
BOOL WriteProcessMemory(
HANDLE hProcess,
(LPVOID lpBaseAddress)0x7FF6CC7DCCD,
(LPCVOID lpBuffer)yourDataBuffer,
(SIZE_T nSize)Sizeof(yourDataBuffer),
(SIZE_T *lpNumberOfBytesWritten)outWritten
);
|
69,299,784 | 69,301,984 | Can I get the raw pointer for a std::stringstream accumulated data with 0-copy? | Here is what I would like to do:
std::stringstream s;
s<<"Some "<<std::hex<<123<<" hex data"<<...;
Having this s, I would very much like to pass it around, and that is possible easily. However, at some point, there is a need to (conceptually) pass it to an interface that only accepts const void */size_t pair which describes the memory region.
As far as I see (would love to stand corrected), there is no way to do that with 0-copy in C++17 and below. One must use .str() which will create a string copy and then take it from there.
As a "hack", this is what I came up with:
struct stringstream_extractor_t {
// this structure will be used to get access to pbase member function which is protected
// the way we do that is to inherit from it
template <typename T>
struct accessor_t : public T {
static const char* data(const accessor_t* pT) { return pT->pbase(); }
};
// get the return type for std::stringstream::rdbuf
using bufferType = std::remove_pointer<decltype(((std::stringstream*)nullptr)->rdbuf())>::type;
// having the std::stringstream::rdbuf result type, we can now create our accessor type
// which will be able to call pbase inside it
using accessorType = accessor_t<bufferType>;
// this is where we deposit the data, in a const manner
const std::string_view _data;
// syntactic sugar: init the _data with the stuff from stream reference
stringstream_extractor_t(std::stringstream& stream) : _data{getBuffer(stream), static_cast<size_t>(stream.tellp())} {}
// syntactic sugar: init the _data with the stuff from stream pointer
stringstream_extractor_t(std::stringstream* pStream) :
_data{pStream ? getBuffer(*pStream) : nullptr, pStream ? static_cast<size_t>(pStream->tellp()) : 0} {}
// this uses the accessor type to grab access to data
static const char* getBuffer(const std::stringstream& stream) {
// we get the buffer and we cast it to our accessor type. This is safe, as we do not
// have any members inside it, just a static function
const accessorType* pBuffer = reinterpret_cast<accessorType*>(stream.rdbuf());
// grab the data now
return accessorType::data(pBuffer);
}
// convenience functionality
inline const char* data() const { return _data.data(); }
inline size_t size() const { return _data.size(); }
};
And here is how it is used, with a C-like interface
std::stringstream s;
s << "Hi there! " << std::hex << 0xdeadbeef;
const stringstream_extractor_t e(s);
write(2, e.data(), e.size());
Yes, I'm aware of the fact that the pointers must be kept alive (the std::stringstream instance), and all the life cycle implications.
Is there a more comfortable non-convoluted way to achieve this quite basic thing: get a buffer out from an output stringstream with move semantics.
I'm clearly missing something, this should not be this hard.
https://godbolt.org/z/G53P6oocb
| Well in C++ 20 you could do this
#include <iostream>
#include <ios>
#include <sstream>
void c_style_func(const char* cp, std::size_t size) {
std::cout << std::string_view (cp,size) << "\n";
}
int main() {
std::stringstream s;
s << "Hi there! " << std::hex << 0xdeadbeef;
auto view = s.view();
c_style_func(view.data(), view.size());
}
using § 29.8.2.4 Page of the standard 1411
basic_string_view<charT, traits> view() const noexcept;
11 Let sv be basic_string_view<charT, traits>.
12 Returns: A sv object referring to the basic_stringbuf’s underlying character sequence in buf:
(12.1) — If ios_base::out is set in mode, then sv(pbase(), high_mark-pbase()) is returned.
(12.2) — Otherwise, if ios_base::in is set in mode, then sv(eback(), egptr()-eback()) is returned.
(12.3) — Otherwise, sv() is returned.
13 [Note: Using the returned sv object after destruction or invalidation of the character sequence underlying
*this is undefined behavior, unless sv.empty() is true. —end note]
|
69,299,925 | 69,300,011 | std: :array -- difference between size() and max_size() | What is the difference between size() and max_size() functions for std: :array in C++?
array<int,5> arr{ 1, 2, 3, 4, 5 };
cout << arr.size();
/* Output : 5 */
array<int, 5> arr{ 1, 2, 3, 4, 5 };
cout << arr.max_size();
/* Output : 5 */
|
What is the difference between size() and max_size() functions for std: :array in C++?
The latter has prefix max_. There is no other practical difference between them for std::array.
The difference is conceptual. size is the current number of elements in the container, and max_size is a theoretical upper bound to how many elements the container could have. Since the number of elements in std::array is constant, the current number of elements is exactly the same as the number of elements there can ever be. For other containers, there is a practical difference.
Using the max_size member function of std::array is conceptually silly. It exists so that std::array conforms to the Container concept (e.g. named requirement), which allows it to be used uniformly with other containers, which is useful within templates.
|
69,300,068 | 69,300,143 | Call of an object of a class type without appropriate operator(). Inside a .cpp file | I declared a class and then an object, but when I want to use my object, it gives me an error. I searched a bit on Google, but didn't understand what my problem is. The way I declared my class / object is the same as I usually do, and this is the first time it doesn't work.
Here's my .cpp:
#include <iostream>
#include "game.h++"
int game_loop(void)
{
char *nam;
Hero *myHero = new Hero();
printf("So what's your name ? : ");
scanf("%s", &nam);
myHero->name(nam); //the error is here
}
and my .h++:
#include <string>
class Hero
{
public:
std::string name;
int race;
int classe;
int level = 0;
int hp = 10;
int mana = 5;
};
| Well, first thing's first, you are trying to use the operator() of a member of type std::string. That operator indeed does not exist.
If you want to set the value of hero->name to nam, you'd have to do something like this:
hero->name = std::string(nam);
Second - why are you using C methods in C++? Using scanf() to input strings is unsafe. You should use fgets(), or C++'s own std::cin.
|
69,300,854 | 69,301,290 | Check if input string has leading or trailing whitespaces in C++? | I am trying to validate a single-line input string in C++11 to see if it contains any leading / trailing whitespaces. My code now looks like this:
bool is_valid(const std::string& s) {
auto start = s.begin();
auto end = s.end();
if (std::isspace(*start) || std::isspace(*end)) {
return false;
}
return true;
}
int main() {
std::string name{};
std::getline(std::cin, name);
if (!is_valid(name)) {
std::cout << "Invalid!";
}
return 0;
}
But now the program can only detect leading whitespaces. For example, for John it would print Invalid! but for Mary it would classify it as valid input, which is not. Does anyone know what's wrong with my program?
| A simple test for std::string::front() and std::string::back() could have been done after testing for the empty string:
bool is_valid(const std::string& s)
{
return s.empty() ||
(!std::isspace(static_cast<unsigned char>(s.front())) &&
!std::isspace(static_cast<unsigned char>(s.back())));
}
|
69,301,510 | 69,301,548 | Static var in loop could be way to optimize in c++? | I think non-static var in loop could make some overhead (construct / destruct for each loop).
Am I right? then why we don't use static var in main-loop?
for(;;){
type1 var1;
type2 var2;
//(var1, var2 construct here )
....
// Do something
....
//(var1, var2 destruct here )
}
for(;;){
static type1 var1;
static type2 var2;
//(var1, var2 don't construct here )
....
// Do something
....
//(var1, var2 don't destruct here )
}
| Your second snippet is not thread safe. These days, you always need to consider thread safety as computational gains have moved from faster clock speeds to more processor cores.
You can trust a compiler to optimise out the first snippet. If you're ever in doubt, check the generated assembly.
|
69,301,732 | 69,302,135 | Integrating C++ class from subfolder in QML | I am currently working on a c++ integration to QML and so far everything worked fine. I got my backend classes exposed and working. Now that I expanded my application I wanted to split my c++ backend into subfolders to have a better project overview. Now I'm running into linking issues where the backend files which are in those subfolders can not be found anymore. Since I am using some libraries that require a certain compiler I am using MSVC 16 and it throws the following error:
Cannot open include file: 'loginstate.h': No such file or directory.
The parsing works fine and QtCreator does not mark the include as wrong.
When building, it creates a file called application.metatypes.json. In said file all the information about the exposed classes is stored. When reading through it, I found that loginstates.h is supposed to be in the root directory where it actually is not, it is in a subfolder of root. When i change it manually to the proper folder, my application runs.
Is there a way to get qmake/moc to generate the proper path for classes in subfolders? What setting am I missing?
The .pro file:
QT = core quick serialport network virtualkeyboard
TEMPLATE = app
CONFIG += qt c++17 warn_on qmltypes
CONFIG -= debug_and_release debug_and_release_target
SOURCES += \
main.cpp \
datetimebackend.cpp \
footerbackend.cpp \
labelbuttonbackend.cpp \
globaluisettings.cpp \
headerbackend.cpp \
scannerbuttonbackend.cpp \
sidebarbackend.cpp
HEADERS += \
businessLogic/loginstate.h \
datetimebackend.h \
footerbackend.h \
globaluisettings.h \
headerbackend.h \
labelbuttonbackend.h \
scannerbuttonbackend.h \
sidebarbackend.h
RESOURCES += qml.qrc
RC_ICONS = ./images/icon.ico
INCLUDEPATH += $$PWD/..
# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH += $$PWD
# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =
QML_IMPORT_NAME = Backend
QML_IMPORT_MAJOR_VERSION = 1
DISTFILES += some qml files
| You get those errors just because some header files are not in path and the compiler cannot find them. As you said that you restructured the directory template, you will only need to add appropriate include paths to the INCLUDEPATH parameter in your .pro file like :
INCLUDEPATH += $$PWD/new/include/path
Do it for every directory where contains a .h file that is not being found by the compiler.
|
69,301,997 | 69,317,133 | Android OpenGL ES 3.0 Skeletal Animations glitch with UBO | I've been spending the better part of the last 2 days hunting down an OpenGL ES bug I've encountered only on some devices. In detail:
I'm trying to implement skeletal animations, using the following GLSL code:
#ifndef NR_BONES_INC
#define NR_BONES_INC
#ifndef NR_MAX_BONES
#define NR_MAX_BONES 256
#endif
in ivec4 aBoneIds;
in vec4 aBoneWeights;
layout (std140) uniform boneOffsets { mat4 offsets[NR_MAX_BONES]; } bones;
mat4 bones_get_matrix() {
mat4 mat = bones.offsets[aBoneIds.x] * aBoneWeights.x;
mat += bones.offsets[aBoneIds.y] * aBoneWeights.y;
mat += bones.offsets[aBoneIds.z] * aBoneWeights.z;
mat += bones.offsets[aBoneIds.w] * aBoneWeights.w;
return mat;
}
#endif
This is then included in the vertex shader and used as such:
vec4 viewPos = mv * bones_get_matrix() * vec4(aPos, 1.0);
gl_Position = projection * viewPos;
The desired output, achieved for example on the Android Emulator (armv8) running on my M1 MacBook Pro is this:
I can't actually capture the output of the faulting device (Espon Moverio BT-350, Android on x86 Intel Atom) sadly, but it's basically the same picture without head, arms or legs.
The uniform buffer bound to boneOffsets, for testing, is created as a std::vector<glm::mat4> with size 256 and is created/bound as such:
GLint buffer = 0;
std::vector<glm::mat4> testData(256, glm::mat4(1.0));
glGenBuffers(1, &buffer);
glBindBuffer(GL_UNIFORM_BUFFER, buffer);
glBufferData(GL_UNIFORM_BUFFER, sizeof(glm::mat4) * testData.size(), &testData[0], GL_DYNAMIC_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, 0, buffer);
glUniformBlockBinding(programId, glGetUniformBlockIndex(programId, "boneOffsets"), 0);
Am I missing a step somewhere in my setup? Is this a GPU bug I'm encountering? Have I misunderstood the std140 layout?
P.S.: After every OpenGL call, I run glGetError(), but nothing shows up. Also nothing in the various info logs for Shaders and Programs.
EDIT
It's the next day, and I've tried skipping the UBO and using a plain uniform array (100 elements instead of 256, my model has 70-ish bones anyway). Same result.
I've also just tried with a "texture". It's a 4*256 GL_RGBAF teture, which is "sampled" as such:
uniform sampler2D bonesTxt;
mat4 read_bones_txt(int id) {
return mat4(
texelFetch(bonesTxt, ivec2(0, id), 0),
texelFetch(bonesTxt, ivec2(1, id), 0),
texelFetch(bonesTxt, ivec2(2, id), 0),
texelFetch(bonesTxt, ivec2(3, id), 0));
}
Still no dice. As a comment suggested, I've checked my bone IDs and Weights. What I send to glBufferData() is ok, but I can't actually check what's on the GPU because I can't get RenderDoc (or anything else) to work on my device.
| I finally figured it out.
When binding my bone IDs I used glVertexAttribPointer() instead of glVertexAttribIPointer().
I was sending the correct type (GL_INT) to glVertexAttribPointer(), but I didn't read this line in the docs:
For glVertexAttribPointer() [...] values will be converted to floats [...]
As usual, RTFM people.
|
69,302,003 | 69,302,290 | How to use c++20 concepts to compile-time enforce match of number of args for given type | I'm using policy-based design, and I have several policies implementation (that use same interface), but one of the policies needs a different number of args for construction.
So i've used in my class variadic template arguments (typename... InitArgs)
and I forward them using std::forward to contructor of policy type.
example:
class Policy1 : public PolicyBase
{
Policy1(int arg1, std::string arg2);
}
class Policy2 : public PolicyBase
{
Policy2(int arg1);
}
template<typename T>
concept PolicyConept = std::is_base_of<PolicyBase, T>::value;
template<PolicyConept T = Policy1, typename... InitArgs>
class PolicyManager
{
public:
PolicyManager(InitArgs... args)
{
_policyState = std::make_unique<T>(std::forward<InitArgs>(args)...);
}
private:
std::unique_ptr<T> _policyState;
}
int main()
{
auto policy1 = std::make_unique<PolicyManager<Policy1>>(1,"2");
auto policy2 = std::make_unique<PolicyManager<Policy2>>(1);
}
I'm looking for a way to use concepts (introduced in C++20), that can perform compile-time check, to ensure the number of arguments provide is enough to build from them the given type.
so would expect the following code to fail at compile time:
int main()
{
auto policy1 = std::make_unique<PolicyManager<Policy1>>(1); // missing argument
}
I was attempting to use the concept std::constructible_from to accomplish that,
but I'm not sure how the syntax would apply for args....
Would appreciate the help
| You need to put a constraint on the constructor.
template <typename... Args>
PolicyManager(Args&&... args) requires std::constructible_from<T, Args&&...>
Note also that the Args template parameter pack should be on the constructor to ensure the arguments are correctly forwarded.
|
69,302,362 | 69,302,664 | Lambda function, arguments and logic in c++ | I am new to using lambda functions in C++. I have been researching the web, and found several articles, explaining the syntax and purpose of lambda function, but I have not come found articles which are clearly giving an explaining how to write the inner logic of a lambda function.
For example
During sorting a vector in c++ in decreasing order:
sort(v1.begin(), v1.end(), [](const int &a, const int &b){return b < a;});
I write the above code. Here, I have a few questions:
Why do I only provide two parameters in the lambda function? Why not three? or why not I give all the n parameter(n is size of vector) and do a logic? I am not trying to find maximum of two elements, I am trying to sort a vector, why should I only consider two values?
Why does a > b gives descending order? Why not b > a? Are there any kind of ordering inside the lambda function?
The return value in the above lambda function is either false(0) or true(1)? Why do I only have to return false(0) or true(1) to sort? Why can't I return a character to sort, like let's suppose for return value 'a' it is ascending and return value 'd' it is descending?
Again
During finding the max even element
itr = max_element(v1.begin(), v1.end(), [](const int &a, const int &b){
if (isEven(a) && isEven(b)) {
return (a < b);
} else
return false;
}
);
I am returning b > a. Rather than a greater than b. ???
Any suggestion would be greatly appreciated.
| Your question has nothing to do with lambdas, but with the std::sort function.
Indeed, if you read the documentation about the third parameter (the comparison function, the lambda in your case), it says:
comparison function object which returns true if the first argument is
less than (i.e. is ordered before) the second.
The signature of the comparison function should be equivalent to the
following:
bool cmp(const Type1 &a, const Type2 &b);
Indeed, there is not need to create a lambda to pass it as the third parameter. You can pass any function object that receives two arguments of type T (the one of your container's elements) and returns bool.
For example, you can do something like this:
#include <vector>
#include <algorithm>
#include <iostream>
struct {
bool operator () (int a, int b){
return a > b;
}
}my_comp;
int main(){
std::vector<int> v={1,2,3};
std::sort(v.begin(), v.end(), my_comp);
for(auto e:v) std::cout << e << " ";
std::cout << std::endl;
}
|
69,302,449 | 69,302,646 | Rearranged vector elements after std::unique | I'm currently working through Stanley Lippman's C++ Primer. In Chapter 10 generic algorithms are introduced.
As an example std::sort, std::unique and the std::vector member function erase shall be used to remove duplicate elements within a vector.
To see how a vectors elements are rearranged by std::unique I tried to print every element just to find that not all elements are printed. However a call to .size() tells that the size of the vector is as expected unchanged.
After compiling the program:
clang++ -std=c++11 -o elimDubs elimDubs.cc
and calling the programm with
./elimDubs the quick red fox jumps over the slow red turtle
The program prints
Size after std::unique: 10
fox jumps over quick red slow the turtle the
which are only 9 of the 10 elements. (red is missing)
Why? For the program it doesn't really matter as the subsequent call of erase is used to remove the duplicate elements anyways, still it irritates me that there are elements missing or at least not being printed.
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
void elimDubs( std::vector<std::string> &words )
{
std::sort( words.begin(), words.end() );
auto end_unique = std::unique( words.begin(), words.end() );
std::cout << "Size after std::unique: "
<< words.size() << std::endl;
for ( const auto &el : words )
std::cout << el << " ";
std::cout << std::endl;
}
int main(int argc, char **argv)
{
std::vector<std::string> sentence;
if ( argc < 2 )
return -1;
std::copy( argv + 1, argv + argc,
std::back_inserter(sentence) );
elimDubs( sentence );
}
| std::unique is a destructive process. Quoting cppreference,
Removing is done by shifting the elements in the range in such a way that elements to be erased are overwritten.
This means that any elements after the new end iterator returned by std::unique are going to be in a valid but unspecified state. They aren't meant to be accessed as they should be removed from the vector with a call to erase.
This is also noted in the note section:
Iterators in [r, last) (if any), where r is the return value, are still dereferenceable, but the elements themselves have unspecified values. A call to unique is typically followed by a call to a container's erase member function, which erases the unspecified values and reduces the physical size of the container to match its new logical size.
|
69,302,496 | 69,303,285 | GNURadio OOT Module - Undefined symbol error | I am implementing a convolutional encoder-decoder OOT Module in GNU Radio 3.8 in C++.
When running the python tests I've written for the encoder and decoder, I get the following error:
ImportError: undefined symbol: _ZN2gr5a3sat13conv_dec_impl9generatorE
The generator variable is declared in the conv_dec_impl header file as:
inline static const bool generator[2][7] = {{1, 0, 0, 1, 1, 1, 1}, {1, 1, 0, 1, 1, 0, 1}}
Also, in the tests' python file, when importing a3sat_swig, I get this error: No module named 'a3sat_swig'
Could it be related to the CMakeLists file?
Any help is welcome.
|
The generator variable is declared in the conv_dec_impl header file as:
inline static const bool generator[2][7] = {{1, 0, 0, 1, 1, 1, 1}, {1, 1, 0, 1, 1, 0, 1}}
Move the generator definition to the .cpp file. Also make sure you don't have a previous version of your OOT block that lacks this symbol already installed.
Also, in the tests' python file, when importing a3sat_swig, I get this error: No module named 'a3sat_swig'
Open python/__init__.py and either change ImportError to ModuleNotFoundError or remove the try and except. See issue 4761
Could it be related to the CMakeLists file?
No, most probably is not related to CMakeLists file.
|
69,302,647 | 69,312,173 | Gmock - matching structures with more than two vairables | Unlike the question in Gmock - matching structures, I'm wondring how I could create a matcher for a struct with >2 members. Let's say I've got a structure of 8 members, and that MyFun() takes a pointer to a SomeStruct_t as an argument.
typedef struct
{
int data_1;
int data_2;
int data_3;
int data_4;
int data_5;
int data_6;
int data_7;
int data_8;
} SomeStruct_t;
SomeStruct_t my_struct;
EXPECT_CALL(*myMock, MyFun(MyMatcher(my_struct)));
Do you have any suggestions/examples on how MyMatcher should be implemented? Or, could I solve this without using a matcher? I'd like to check each element of my_struct.
| MATCHER_P(MyMatcher, MyStruct, "arg struct does not match expected struct")
{
return (arg.data_1 == MyStruct.data_1) && (arg.data_2 == MyStruct.data_2) &&
(arg.data_3 == MyStruct.data_3) && (arg.data_4 == MyStruct.data_4) &&
(arg.data_5 == MyStruct.data_5) && (arg.data_6 == MyStruct.data_6) &&
(arg.data_7 == MyStruct.data_7) && (arg.data_8 == MyStruct.data_8);
}
This solved my problem. Though it would be nice with more examples in the gmock documentaion.
|
69,302,800 | 71,861,246 | A question about vcpkg and pcl/visualization | first, I used :
./vcpkg install pcl
to install pcl. However, I don't notice that this command could not install vtk and use pcl/visualization. I succeed in installing and using pcl(except visualiztion).
So, I try follow :
./vcpkg install pcl[vtk,qt] --rescure
Actually, when I wanted to use I could still not #include<pcl/visualiztion/..>
| I had to run it the following way to fix this issue:
vcpkg install pcl[vtk]:x64-windows --featurepackages --recurse
Not sure whether x64-windows specifier is important, but keep in mind that VCPKG installs x86 libraries by default. Also please not that the option you have used is misspelled: it is --recurse, not --rescure.
If you are using CMake, remember to use the toolchain file:
cmake -B [build directory] -DCMAKE_TOOLCHAIN_FILE=[path to vcpkg]/scripts/buildsystems/vcpkg.cmake
|
69,303,706 | 69,303,747 | traversing a binary tree in postorder method | I'm new in binary tree, i want to traverse the 2 node in the binary tree but the output result into a random number or no output.
Here's the driver function:
int main(){
node *root, *num2;
bt tree;
root = new node;
root->data = 12;
root->left = num2;
root->right = NULL;
tree.root = root;
num2 = new node;
num2->data = 10;
num2->right = NULL;
num2->left =NULL;
std::cout<<"Postorder: ";
tree.postorder();
std::cout<<"\n";
return 0;
}
Binary traversal methods:
struct bt{
node *root = nullptr;
public:
void postorder(){
postorder_impl(root);
}
private:
void postorder_impl(node *start){
if(!start) return;
postorder_impl(start->left);
postorder_impl(start->right);
std::cout << start->data << " ";
}
};
| When you write root->left = num2; num2 is uninitalized yet. So it is a random adres in memory. So root->left (and start->left inside the postorder(); function). So you will call the postorder_impl(); function with an undefined adress will be is a random memoryadres even after you set num2 to a valid node.
Put num2 = new node; before it. root->left = num2;
|
69,303,724 | 69,303,999 | Why does basic_istream_view inherit view_interface? | basic_istream_view is a simple input_range in C++20 and has only one begin() and end() function:
template<movable Val, class CharT, class Traits>
requires default_initializable<Val> &&
stream-extractable<Val, CharT, Traits>
class basic_istream_view : public view_interface<
basic_istream_view<Val, CharT, Traits>> {
public:
constexpr iterator begin();
constexpr default_sentinel_t end() const noexcept;
};
It inherits view_interface which is defined in [view.interface] as:
template<class D>
class view_interface {
public:
constexpr bool empty() requires forward_range<D>;
constexpr explicit operator bool()
requires requires { ranges::empty(derived()); };
constexpr auto data() requires contiguous_iterator<iterator_t<D>>;
constexpr auto size() requires forward_range<D>;
constexpr decltype(auto) front() requires forward_range<D>;
constexpr decltype(auto) back() requires bidirectional_range<D>;
template<random_access_range R = D>
constexpr decltype(auto) operator[](range_difference_t<R> n);
};
You can see that almost all member functions of view_interface require D to be forward_range, while operator bool() requires ranges::empty(derived()) to be well-formed, which also requires D to be forward_range.
It seems that the only purpose of basic_istream_view inheriting view_interface is to model a view since view requires view_base or view_interface to be inherited.
But if you want to make basic_istream_view a view, why not just inherit it directly from view_base? I can't see any benefit from inheriting view_interface except for the cost of template instantiation.
So, why does basic_istream_view inherit the view_interface instead of view_base? Does it have historical reasons?
| Just because the member functions of view_interface today all need forward ranges doesn't mean that we will never add member functions in the future that can work on input ranges too.
Also, why not?
|
69,304,028 | 69,304,295 | How to convert tuple into initializer list | I make large tuple with std::make_tuple function.
something like this
template <class ...T>
QCborArray array(const T&... args) {
return {args...};
}
but with tuple instead of parameter pack
| You can use std::apply and a variadic lambda to do this. That would look like
template <class Tuple>
QCborArray array(Tuple&& tuple) {
return std::apply([](auto&&... args) { return QCborArray{args...}; },
std::forward<Tuple>(tuple));
}
|
69,304,436 | 69,304,767 | How to parse CSV by columns and save into arrays C++ | I'm a new learner of C++. I have some data saved in Data.csv like this:
S0001 S0002 S0003 S0004 ...
0 10.289461 17.012874
1 11.491483 13.053712
2 10.404887 12.190057
3 10.502540 16.363996 ... ...
4 11.102104 12.795502
5 13.205706 13.707030
6 10.544555 12.173467
7 10.380928 12.578932
... ... ... ... ...
I need values column by column to do calculations (column average, moving average, etc), so I want to parse by columns and save them into arrays.
I read these answers but didn't find what I want. What I did is
void read_file(std::vector<std::string>& v, std::string filename){
std::ifstream inFile(filename);
std::string temp;
if (!inFile.is_open()) {
std::cout<<"Unable to open the file"<<std::endl;
exit(1);
}
while (getline(inFile, temp)) {
v.push_back(temp);
}
inFile.close();
}
int main()
{
std::string filename = "Book1.csv";
std::vector<std::string> vec;
read_file(vec, filename);
std::cout<<vec[1]<<std::endl;
}
I can only get values line by line. But how can I parse the file and get values by column?
| You can only read text file line-by-line. If you only need ONE column (unlikely), you could parse that value out of the line and push it into a vector.
If you need to load ALL columns in one pass, create a vector of vectors and push parsed values into a different column vectors.
|
69,304,461 | 69,588,378 | Code algorithms inside React Native project | I'm new to React Native and the app I'm building needs to run some algorithms. Is there any way to run functions from a lower-level programming language inside the React app?
I need this because the algorithms I'm running are really time-consuming and it would take way too much time to run it in JavaScript.
Is there any way I can run some C/C++ code from inside the App? Or are there any other programming languages that can be run from the app that is faster?
| This is not a React-specific problem. You want to run native c/c++ logic inside a js/typescript program.
Either use assembly script (similar to typescript) or web assembly (convert native c/c++ to wasm which can be imported in any js/typescript environment).
https://www.youtube.com/watch?v=9lxnm9a-Yi8&ab_channel=Maniyar
https://developer.mozilla.org/en-US/docs/WebAssembly/C_to_wasm
|
69,304,677 | 69,304,708 | OPCUA sdk include path | I have trouble with include uaplatformlayer.h in example from OPCUA client example.
I found this example in SDK. I tried to do own makefile, to build example client lesson01.
I use Visual Studio Code. It can't find this .h file.
#include "uaplatformlayer.h"
#include "sampleclient.h"
int main(int, char*[])
{
UaStatus status;
// Initialize the UA Stack platform layer
UaPlatformLayer::init();
// Create instance of SampleClient
SampleClient* pMyClient = new SampleClient();
return 0;
}
it still replies...
g++ -g -Wall -c client_cpp_sdk_tutorial.cpp
client_cpp_sdk_tutorial.cpp:1:10: fatal error: uaplatformlayer.h: Adresář nebo soubor neexistuje
1 | #include "uaplatformlayer.h"
| ^~~~~~~~~~~~~~~~~~~
compilation terminated.
make: *** [Makefile:9: client_cpp_sdk_tutorial.o] Chyba 1
The terminal process "bash '-c', '/home/michal/Dokumenty/OPCUA_adapter/sdk/examples/client_gettingstarted/lesson01/build.sh'" failed to launch (exit code: 2)
I think my problem is in makefile, but I don't have any idea where is the mistake.
Could anyone help me, please?
Does anyone experiance with OPCUA SDK?
cc=g++
cflags=-g -Wall
libflags=-L/home/michal/Dokumenty/OPCUA_adapter/sdk/lib -luamoduled -luamodelsd -lcoremoduled -luabasecppd -luastackd -lxmlparsercppd -luapkicppd -luaclientcppd -lxml2 -lssl -lcrypto
includes=-I/home/michal/Dokumenty/OPCUA_adapter/sdk/include/uabasecpp -I/home/michal/Dokumenty/OPCUA_adapter/sdk/include/uastack
objfiles=client_cpp_sdk_tutorial.o sampleclient.o
vystup=aplikace
%.o : %.cpp
$(cc) $(cflags) -c $<
# startovaci pravidlo
vychozi: $(vystup)
# zavislosti
dep:
$(cc) -MM *.cpp >dep.list
-include dep.list
clean:
rm aplikace $(objfiles)
# slinkování aplikace
$(vystup): $(objfiles)
$(cc) $(cflags) $(objfiles) $(includes) $(libflags) -o $@
| You need to add "includes" to the recipe for the .o files:
%.o : %.cpp
$(cc) $(cflags) $(includes) -c $<
|
69,304,852 | 69,305,064 | Iterate through container of structs by specific member | I have a function
template<typename I> double mean(I begin, I end)
{
double s = 0;
size_t n = 0;
while(begin != end)
{
s += *begin++;
++n;
}
return s / n;
}
and a vector of structs T:
struct T
{
double a;
double b;
};
vector<T> v;
Is there an elegant way to compute mean of all a members of structs in v? Some way to wrap vector<T>::iterator to iterator that extracts a member?
| You would need to tell mean() which member of T to look at. You can use a pointer-to-data-member for that, eg:
template<typename Iter, typename T>
double mean(Iter begin, Iter end, double (T::*member))
{
double s = 0;
size_t n = 0;
while (begin != end)
{
s += (*begin++).*member;
++n;
}
return s / n;
}
struct T
{
double a;
double b;
};
vector<T> v;
// fill v...
double m = mean(v.begin(), v.end(), &T::a/*or b*/);
Online Demo
You could take this further by getting rid of your manual loop and use std::accumulate() instead, eg:
#include <numeric>
template<typename Iter, typename T>
double mean(Iter begin, Iter end, double (T::*member))
{
size_t n = 0;
double s = std::accumulate(begin, end, 0.0,
[&](double acc, const T &t){ ++n; return acc + t.*member; }
);
return s / n;
}
Online Demo
In which case, you could just get rid of mean() altogether:
#include <numeric>
vector<T> v;
// fill v...
double m = accumulate(v.begin(), v.end(), 0.0,
[](double acc, const T &t){ return acc + t.a/*or b*/; }
) / v.size();
Online demo
|
69,305,080 | 69,305,478 | How to alternate sort between even and odds ascendingly in C++? | I have an array of equal even and odd integers. I want to sort the array such that array would be in that pattern: even1, odd1, even2, odd2, even3, odd3,.. and so on where even1 <= even2 <= even3 and odd1 <= odd2 <= odd3.
For instance if array is [1, 2, 3, 4, 5, 6]. Sorted array would be [2, 1, 4, 3, 6, 5].
I want to do that using std::sort compare function. But unfortunately I couldn't. I believe it's impossible to do that.
bool cmp(int lhs, int rhs) {
// couldn't write anything
}
| If you create a compare function that puts all odd numbers before even and simply compares within those groups, you can in one sort have all odds sorted followed by all evens sorted.
You'd then need to swap them correctly.
Something like this
bool cmp(int lhs, int rhs) {
if ((lhs ^ rhs) & 1) // different oddness
return lhs & 1; // place odds first
return lhs < rhs;
}
|
69,305,116 | 69,305,150 | How to search for a substring on a LPCSTR? | typedef _Null_terminated_ CONST CHAR *LPCSTR, *PCSTR;
// .....
LPCSTR foo = "hello world";
How do I search if foo contains hello?
| You can use strstr
LPCSTR foo = "hello world";
char * pch = strstr (foo,"hello");
|
69,305,443 | 69,365,871 | How does this array indexer helps coalesced memory access? | At here, it is defined this function:
template <typename T, typename = std::enable_if_t<is_uint32_v<T> || is_uint64_v<T>>>
inline T reverse_bits(T operand, int bit_count)
{
// Just return zero if bit_count is zero
return (bit_count == 0) ? T(0)
: reverse_bits(operand) >> (sizeof(T) * static_cast<std::size_t>(bits_per_byte) -
static_cast<std::size_t>(bit_count));
}
At a later point, this function is used to store elements in a scrambled way into an array:
inv_root_powers_[reverse_bits(i - 1, coeff_count_power_) + 1].set(power, modulus_);
The justification for this is so that the memory access is coalesced. However, I don't know why such random values would make it easier for the memory access. For example, here are some values:
reverse_bits(3661, 12) +1 = 2856
reverse_bits(3662, 12) +1 = 1832
reverse_bits(3663, 12) +1 = 3880
reverse_bits(3664, 12) +1 = 168
reverse_bits(3665, 12) +1 = 2216
reverse_bits(3666, 12) +1 = 1192
reverse_bits(3667, 12) +1 = 3240
reverse_bits(3668, 12) +1 = 680
reverse_bits(3669, 12) +1 = 2728
seems like things are stored far apart.
| You're right - the accesses you see in NTTTables::initialize are random-access and not serial. It is slower because of this "scramble". However, most of the work happens only later in DWTHandler::transform_to_rev, when the transform itself is applied.
There, they need to access the roots by reverse-bits order. The array being pre-scrambled means all the accesses to this array are now serial: you can see this in the r = *++roots; lines.
The reverse-bits access pattern has a good, real reason - it's because they're doing a variant of the Finite Fourier Transform (FFT). The memory access patterns used in those algorithms (sometimes called butterflies) are done in a bit-reverse order.
|
69,305,896 | 69,305,954 | Store/output a number bigger than unsigned long long can store | With user given number (n) for example n=5, I calculate the sum of 10000,10001,10002....99999.
Works up until n=17, then I get a negative number or eventually a zero.
So my question is how do I store a number bigger than unsigned long long lets me
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
unsigned long long n, sum;
cin>>n;
unsigned long long start=pow(10, n-1);
unsigned long long finish=pow(10, n)-1;
sum=((finish-start+1)*(start+finish))/2;
cout<<sum<<endl;
return 0;
}
| In case you don't want bother with installing some big number library like GMP, or you do it for some site like code wars then you have basically two options:
A) create your own data type to hold bigger numbers ( in this case not really recommended, as number may be insanely huge).
B) hold it as a string/char table and write a function to process adding values.
|
69,306,186 | 69,306,511 | Thread safety of Vector of atomic bool | If I have a vector:
std::vector<std::atomic_bool> v(8);
and assuming I won't modify its size post creation, is it thread safe to call:
bool result = v[2].compare_exchange_strong(false, true);
* the values 8, 2, false and true are just given as an example use case.
| The OP appears to be asking whether multiple threads can evaluate
v[2].compare_exchange_strong(false, true)
when such evaluations are potentially concurrent, without causing a data race.
This will not compile because compare_exchange_strong requires an lvalue as its first argument. I will assume that this issue is corrected.
The answer is yes. According to [container.requirements.dataraces]/1:
For purposes of avoiding data races (16.5.5.10), implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, back, data, find, lower_bound, upper_bound, equal_range, at and, except in associative or unordered associative containers, operator[].
This implies that evaluating v[2] is not allowed to modify the vector (nor any internal static data that might be shared between threads) and thus may not race with the same evaluation in another thread. The compare_exchange_strong operation is being performed on an atomic object, so it's impossible for it to race with anything.
|
69,306,238 | 69,306,327 | Why are the integers in the array negative after reversing the array and reversing back to the original array? | void reverseArray(int arrayLength, int sequence[]){
int temparr[arrayLength];
int *pointStart = sequence;
int *pointEnd = sequence + arrayLength - 1;
for(int i = 0; i < arrayLength; i++){
temparr[i] = *pointEnd - i;
}
for(int i = 0; i < arrayLength; i++){
sequence[i] = temparr[i];
}
}
void printArray(int arrayLength, int sequence[]){
for(int i = 0; i < arrayLength; i++, sequence++){
std::cout << *sequence << " ";
}
std::cout << "\n";
}
int main(int argc, char **argv) {
const int num = 50;
int arr[num];
for (int i = 0; i < num; i++){
arr[i] = i;
}
reverseArray(num, arr);
std::cout << "Printing reverse array...\n";
printArray(num, arr);
reverseArray(num, arr);
std::cout << "Printing reverse of the reverse array...\n";
printArray(num, arr);
ASSERT_EQ(0, arr[0]);
ASSERT_EQ(24, arr[24]);
ASSERT_EQ(49, arr[49]);
return 0;
}
I am able to reverse the array, but when I put the "reversed" array back into the function, it seems to be of negative elements. I am not sure where this happens... Anything will help! The unit testing isn't the problem, but it is a part of the code.
[1]: https://i.stack.imgur.com/MkfBC.png
| You have a bug with this line:
temparr[i] = *pointEnd - i;
Here you are dereferencing the pointEnd pointer and subtracting i from the resulting integer.
What you meant to write is:
temparr[i] = *( pointEnd - i );
Here you are subtracting i from the pointEnd pointer, then dereferencing.
That being said, instead of doing confusing pointer arithmetic why not do something like this instead:
temparr[ i ] = sequence[ arrayLength - i ];
|
69,306,789 | 69,306,847 | Use constexpr for optional configuration | Right now, I use something like the following to provide configuration to "sub-projects" within my code:
//_config.h
#ifndef _CONFIG_H
#define _CONFIG_H
#if defined(USE_CONFIG_H) && USE_CONFIG_H == 1
#include <config.h>
#endif
#ifndef CONFIG_OPTION_1
//Default value for CONFIG_OPTION_1
#define CONFIG_OPTION_1 10
#endif
#ifndef CONFIG_OPTION_2
//Default value for CONFIG_OPTION_2
#define CONFIG_OPTION_2 20
#endif
#endif
That way I can include _config.h in my sub-project, use the configuration values, and "override" them if necessary be defining USE_CONFIG_H at compile time and placing config.h in the include path.
Now, I have been trying to convert over as much old C-style code as I can to take advantage of the safer alternatives in C++. Once of these is converting constants defined using macros into constexpr values. For example
constexpr unsigned int CONFIG_OPTION_1 = 10;
The problem I am having is, how do I replicate the same behavior I had with macros being able to conditionally override the default configuration values?
| Macros are the only way to make conditional compilation, so you cannot get rid of them entirely. But you can use the macro to initialise a variable:
constexpr unsigned int NON_MACRO_CONFIG_OPTION_1 = CONFIG_OPTION_1;
Thereby getting the benefits of types.
|
69,306,813 | 69,306,927 | Trying to compare a string to a a value with tertiary/conditional operator and it doesn't work | just learning C++ here.
#include <iostream>
#include <string>
int main()
{
char name[1000];
std::cout << "What is your name?\n";
std::cin.get(name, 50);
name == "Shah Bhuiyan" ? std::cout << "Okay, it's you\n" : std::cout<< "Who is this?\n";
}
So here I wrote a program where I created a variable name[100]. I use the cin iostream object thing to take input for the variable name. If the name is equal to my name (as seen in name == "Shah Bhuiyan" :) then output the first thing or output 'Who are you?'
Instead of outputting 'Oh, it's you' it outputs 'who is this?'
Why doesn't this work?
| Your code is using arrays of characters. Any comparisons using == will compare their memory address. Since name and "Shah Bhuiyan" are two distinct arrays of characters, it will always be false.
The obvious solution is to use c++ strings from the standard library:
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "What is your name?\n";
std::getline(std::cin, name);
name == "Shah Bhuiyan" ? std::cout << "Okay, it's you\n" : std::cout<< "Who is this?\n";
}
The std::string type has operators defined that do the right thing here, and will compare the values of each.
|
69,307,137 | 69,308,608 | JNI Unsatisfied Link Error in Eclipse Can't find dependent Libraries | I'm trying to invoke a C++ function from java that uses C++-style strings. The program executes just fine when I'm using C-style strings but just as I declare std::string somehow it can't find dependent libraries anymore. I checked my includes folder in eclipse environment and it does contain <string> library and all its dependencies.
package test_strings;
public class TestString {
static {
System.load("C:\\Users\\aurok\\eclipse-workspace\\native_cpp\\Debug\\libnative_cpp.dll");
}
public native String sayHelloC();
public native String sayHelloCpp();
public static void main(String[] args) {
TestString test = new TestString();
System.out.println(test.sayHelloC());
System.out.println(test.sayHelloCpp());
}
}
And this is my native file:
#include "test_strings_TestString.h"
#include<string>
using namespace std;
JNIEXPORT jstring JNICALL Java_test_1strings_TestString_sayHelloC
(JNIEnv *env, jobject thisObj){
jstring str = env->NewStringUTF("Hello World C-style !!");
return str;
}
JNIEXPORT jstring JNICALL Java_test_1strings_TestString_sayHelloCpp
(JNIEnv *env, jobject thisObj){
//std::string str = "Hello World C++ style !!";
//return env->NewStringUTF(str.c_str());
return env->NewStringUTF("Hello World C++ style !!");
}
This code compiles fine and runs well from java but as soon as I try to use the std::string version(commented) the code compiles and the dynamic library is created but on running the java code I get the following error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Users\aurok\eclipse-workspace\native_cpp\Debug\libnative_cpp.dll: Can't find dependent libraries
at java.base/jdk.internal.loader.NativeLibraries.load(Native Method)
at java.base/jdk.internal.loader.NativeLibraries$NativeLibraryImpl.open(NativeLibraries.java:383)
at java.base/jdk.internal.loader.NativeLibraries.loadLibrary(NativeLibraries.java:227)
at java.base/jdk.internal.loader.NativeLibraries.loadLibrary(NativeLibraries.java:169)
at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2383)
at java.base/java.lang.Runtime.load0(Runtime.java:746)
at java.base/java.lang.System.load(System.java:1857)
at test_strings.TestString.<clinit>(TestString.java:6)
I have searched various sources for a possible explanation but couldn't find one. Guys, help me!
| <string> is a header file, and if your C++ code containing #include <string> directive compiles this means that paths of standard include folders are configured correctly.
However, depending on how your project is configured to be linked to the C and C++ runtime libraries (statically or dynamically), the resulting executable may or may not depend on additional DLLs. (For example, in case of Microsoft Visual Studio 2019 C++ compiler, the C runtime library DLL is vcruntime140.dll and C++ runtime library DLL is msvcp140.dll.)
Using std::string probably causes your executable to depend on the C++ runtime library DLL (in addition to the C runtime DLL), and perhaps it is not found in the same folder as the executable (and not in the DLL search path).
On Windows, C runtime DLL is often already available system-wide, but C++ runtime DLL needs to be either installed (using the Microsoft Visual C++ Redistributable package) or placed into the same folder along the executable itself.
Another option is to link runtime libraries statically, so the resulting executable won't have those DLL dependencies. But usually, dynamic linking is preferred.
Note that depending on which C++ compiler you are using with your Eclipse IDE — either GCC (G++), Clang, MSVC or some another — the required C++ runtime DLL will have a different filename.
|
69,307,440 | 69,307,588 | Limit code duplication when decorating a function | I’m fairly new to programming in c++ and would like to ask how to implement something in the most efficient way. Let’s say I got a class A with two functions foo and bar. Main will instantiate and object of A and will call foo. This class does something computationally expensive, where foo might call bar and vice versa, backtrack and so on until some result is computed. I now would like to implement something like a decorator for this class where the function bar now does the same as before but before returning e.g., prints some intermediate result, while keeping the original implementation available for cases in which these intermediate results are not wanted. Everything else stays the same.
I wonder I would implement something like this in the best way. I could of course add some if statement at the end of bar in class A and check some member variable which is set in main, but as these functions will be called a lot, this would add many additional checks which are not really needed, as one check in main would be sufficient. I could also create a copy of class A, let’s call it B, and modify bar there. But this would duplicate most of the code and would require subsequent changes to be made to both A and B. I could also make function bar in A virtual and have B derive from A and overwrite it, but then I would just simply have these checks in form of the dispatching decisions, wouldn’t I?
| I would recommend to use a bool parameter
class A{
public:
void foo(/*params*/,bool should_print=false){
if (should_print){
//print
}
}
void bar(/*params*/,bool should_print=false){
if (should_print){
//print
}
}
};
If you want to print set the parameter should_print to true, otherwise don't pass it.
You can also use template for flag. so (INside class A)
template<bool should_print>
void bar(/*params*/){
if constexpr (should_print){
//print
}
}
This will evaluate the if at compile-time so it will be even faster, but you will have to define template-funkctions in the heather for the class not in it's .cpp
Note if constexpr only works from c++17 you can have a regular if if you use an older standard. any competent compiler will evauleate the if compile-time that way too
|
69,307,463 | 69,307,559 | C++ Self defined function declaration error: unknown type name | I am using this to declare a user defined function to calculate the discriminant for quadratic equations:
double discriminant(double a, b, c){
return b * b - 4 * a * c;
}
But for some reason I get the following errors:
Error: unknown type name 'b'
double calcDiscriminant(double a, b, c){
^
error: unknown type name 'c'
double calcDiscriminant(double a, b, c){
^
error: use of undeclared identifier 'b'
return b * b - 4 * a * c;
^
error: use of undeclared identifier 'b'
return b * b - 4 * a * c;
^
error: use of undeclared identifier 'c'
I'm defining the function right after
using namespace std;
So I really don't understand what I'm doing wrong here? I actually found this elsewhere and it's supposed to be a valid function declaration but I can't get it to work.
| When we declare a function with parameters then we have to write data-type of every parameter respectively. So, in function declaration where you have written this:
double discriminant(double a, b, c) {
return b * b - 4 * a * c;
}
Declare it like this:
double discriminant(double a, double b, double c) {
return b * b - 4 * a * c;
}
|
69,307,512 | 69,307,810 | How to copy every N-th byte(s) of a C array | I am writing bit of code in C++ where I want to play a .wav file and perform an FFT (with fftw) on it as it comes (and eventually display that FFT on screen with ncurses). This is mainly just as a "for giggles/to see if I can" project, so I have no restrictions on what I can or can't use aside from wanting to try to keep the result fairly lightweight and cross-platform (I'm doing this on Linux for the moment). I'm also trying to do this "right" and not just hack it together.
I'm using SDL2_audio to achieve the playback, which is working fine. The callback is called at some interval requesting N bytes (seems to be desiredSamples*nChannels). My idea is that at the same time I'm copying the memory from my input buffer to SDL I might as well also copy it in to fftw3's input array to run an FFT on it. Then I can just set ncurses to refresh at whatever rate I'd like separate from the audio callback frequency and it'll just pull the most recent data from the output array.
The catch is that the input file is formatted where the channels are packed together. I.E "(LR) (LR) (LR) ...". So while SDL expects this, I need a way to just get one channel to send to FFTW.
The audio callback format from SDL looks like so:
void myAudioCallback(void* userdata, Uint8* stream, int len) {
SDL_memset(stream, 0, sizeof(stream));
SDL_memcpy(stream, audio_pos, len);
audio_pos += len;
}
where userdata is (currently) unused, stream is the array that SDL wants filled, and len is the length of stream (I.E the number of bytes SDL is looking for).
As far as I know there's no way to get memcpy to just copy every other sample (read: Copy N bytes, skip M, copy N, etc). My current best idea is a brute-force for loop a la...
// pseudocode
for (int i=0; i<len/2; i++) {
fftw_in[i] = audio_pos + 2*i*sizeof(sample)
}
or even more brute force by just reading the file a second time and only taking every other byte or something.
Is there another way to go about accomplishing this, or is one of these my best option? It feels kind of kludgey to go from a nice one line memcpy to send to the data to SDL to some sort of weird loop to send it to fftw.
| Very hard OP's solution can be simplified (for copying bytes):
// pseudocode
const char* s = audio_pos;
for (int d = 0; s < audio_pos + len; d++, s += 2*sizeof(sample)) {
fftw_in[d] = *s;
}
If I new what fftw_in is, I would memcpy blocks sizeof(*fftw_in).
|
69,307,927 | 69,307,949 | Variadic template constructor to fill internal vector of std::variant | I got the following class
class A {
std::string name;
std::vector<std::variant<int,float>> data;
};
my goal is to have a constructor to fill this class with variable number of argument. Examples
A("hello", 1, 2.0, 1)
A("hello", 1, 2.0, 1.2)
....
I tried something like
template <typename... ARGS>
A(std::string n, ARGS... arguments) : name(n), data({arguments...}) {}
But the compiler complains that
non-constant-expression cannot be narrowed from type 'float' to 'std::vector::size_type' in initializer list.
| You trying to call the constructor of data a bunch of times in the initializer list. Remember that variadic templates are unfolded at compile time. You will likely need to handle this outside the initializer list. Something like:
template <typename... ARGS>
A(std::string n, ARGS... arguments) : name(n) {
data.reserve(sizeof...(T));
(data.emplace_back(arguments), ...);
}
Assuming you have fold expressions (AKA c++17). Here is a live example. As a further note, your variant should be a double, or you should specify your input with 2.0f to avoid a narrowing conversion.
|
69,308,319 | 69,309,050 | Creating a COM pointer that supports range-based iteration | Iterating over certain COM collection objects can be cumbersome, so I'm trying to create some COM pointers that support range-based iteration. They're derived from CComPtr. For example, here's an IShellItemArray pointer that I came up with that allows range-based iteration over its IShellItems (so you can iterate over it by just doing for (const auto psi : psia) ):
class CShellItemArrayPtr : public CComPtr<IShellItemArray>
{
public:
using CComPtr::CComPtr;
private:
class CIterator
{
public:
CIterator(IShellItemArray* psia) : m_hr(S_FALSE)
{
HRESULT hr;
hr = psia->EnumItems(&m_pesi);
if (SUCCEEDED(hr))
++*this;
}
const CIterator& operator++ ()
{
m_psi.Release();
m_hr = m_pesi->Next(1, &m_psi, NULL);
return *this;
}
BOOL operator!= (const HRESULT hr) const
{
return m_hr != hr;
}
IShellItem* operator* ()
{
return m_psi;
}
private:
CComPtr<IShellItem> m_psi;
CComPtr<IEnumShellItems> m_pesi;
HRESULT m_hr;
};
public:
CIterator begin() const
{
return CIterator(p);
}
HRESULT end() const
{
return S_FALSE;
}
};
Similarly, here's an IShellWindows pointer I came up with that allows range-based iteration over its individual IWebBrowser2s:
class CShellWindowsPtr : public CComPtr<IShellWindows>
{
public:
using CComPtr::CComPtr;
private:
class CIterator
{
public:
CIterator(IShellWindows* psw) : m_hr(S_FALSE)
{
HRESULT hr;
CComPtr<IUnknown> punk;
hr = psw->_NewEnum(&punk);
if (SUCCEEDED(hr))
{
hr = punk->QueryInterface(&m_pev);
if (SUCCEEDED(hr))
++*this;
}
}
const CIterator& operator++ ()
{
m_pwb2.Release();
CComVariant var;
m_hr = m_pev->Next(1, &var, NULL);
if (m_hr == S_OK)
var.pdispVal->QueryInterface(&m_pwb2);
return *this;
}
BOOL operator!= (const HRESULT hr) const
{
return m_hr != hr;
}
IWebBrowser2* operator* () const
{
return m_pwb2;
}
CComPtr<IWebBrowser2> m_pwb2;
CComPtr<IEnumVARIANT> m_pev;
HRESULT m_hr;
};
public:
CIterator begin() const
{
return CIterator(p);
}
HRESULT end() const
{
return S_FALSE;
}
};
My question is whether there's a smart way of abstracting out this iteration behavior into a more generalized (likely templated) class. I'm not really sure how to go about it, or if it's practically possible. Thank you for any input.
| All IEnum... interfaces have a common design, even though they output different element types. That design can lend itself to C++ templates, so I would suggest separating out CIterator into a standalone template class that can iterate any IEnum... interface, and then have CShellWindowsPtr and CShellItemArrayPtr make use of that class. For example
void CEnumRelease(CComVariant &value)
{
value.Clear();
}
template <typename IntfType>
void CEnumRelease(CComPtr<IntfType> &value)
{
value.Release();
}
// other overloads as needed...
template <typename Intf>
void CEnumTransform(CComVariant &src, CComPtr<Intf> &dest)
{
if (src.vt & VT_TYPEMASK) == VT_UNKNOWN) {
IUnknown *punk = (src.vt & VT_BYREF) ? *(src.ppunkVal) : src.punkVal;
if (punk) punk->QueryInterface(IID_PPV_ARGS(&dest));
}
else if ((src.vt & VT_TYPEMASK) == VT_DISPATCH) {
IDispatch *pdisp = (src.vt & VT_BYREF) ? *(src.ppdispVal) : src.pdispVal;
if (pdisp) pdisp->QueryInterface(IID_PPV_ARGS(&dest));
}
}
template <typename SrcIntf, typename DestIntf>
void CEnumTransform(CComPtr<SrcIntf> &src, CComPtr<DestIntf> &dest)
{
if (src) src->QueryInterface(IID_PPV_ARGS(&dest));
}
// other overloads as needed...
#include <type_traits>
template<typename IEnumType, typename ElementType, typename IntermediateType = ElementType>
class CEnumIterator
{
public:
CEnumIterator() : m_enum()
{
}
CEnumIterator(CComPtr<IEnumType> &enum) : m_enum(enum)
{
++*this;
}
CEnumIterator& operator++ ()
{
CEnumRelease(m_currentValue);
if (m_enum) {
if constexpr (!std::is_same_v<IntermediateType, ElementType>) {
IntermediateType tmp;
if (m_enum->Next(1, &tmp, NULL) != S_OK)
m_enum.Release();
else
CEnumTransform(tmp, m_currentValue);
}
else {
if (m_enum->Next(1, &m_currentValue, NULL) != S_OK) {
m_enum.Release();
}
}
return *this;
}
bool operator == (const CEnumIterator &rhs) const
{
return m_enum == rhs.m_enum;
}
bool operator != (const CEnumIterator &rhs) const
{
return m_enum != rhs.m_enum;
}
ElementType& operator* ()
{
return m_currentValue;
}
private:
CComPtr<IEnumType> m_enum;
ElementType m_currentValue;
};
class CShellItemArrayPtr : public CComPtr<IShellItemArray>
{
public:
auto begin() const
{
CComPtr<IEnumShellItems> enum;
if (p) p->EnumItems(&enum);
return CEnumIterator<IEnumShellItems, CComPtr<IShellItem>>(enum);
}
auto end() const
{
return CEnumIterator<IEnumShellItems, CComPtr<IShellItem>>();
}
};
class CShellWindowsPtr : public CComPtr<IShellWindows>
{
public:
auto begin() const
{
CComPtr<IEnumVARIANT> enum;
if (p) {
CComPtr<IUnknown> punk;
if (SUCCEEDED(p->_NewEnum(&punk) && punk)
punk->QueryInterface(IID_PPV_ARGS(&enum));
}
return CEnumIterator<IEnumVARIANT, CComPtr<IWebBrowser2>, CComVariant>(enum);
}
auto end() const
{
return CEnumIterator<IEnumVARIANT, CComPtr<IWebBrowser2>, CComVariant>();
}
};
|
69,308,340 | 69,308,401 | How to input 2dimensional array using pointers in c++ | void get(int r,int c,int *ptr){
int i,j,k;
cout<<"Enter Elements of a matrix:"<<endl;
for(i=0;i<r;i++){
for(j=0;j<r;j++){
cin>>k;
*(ptr + (i*c) + j)=k;
}
}
}
This is my code.
*(ptr + (i*c) + j)=k;
Can anyone explain how the above line of code works?
| A pointer is an address in memory where some piece of information is stored. This address takes the form of a number. How many bits that number uses is platform-dependent.
Since that address is a number, we can do math with it.
*(ptr + (i*c) + j)=k;
Can be the following when we understand operator precedence and use whitespace.
*(ptr + i * c + j) = k;
We're adding the product of i and c; and then j to the pointer. Then we're dereferencing that whole thing and copying rhe value of k into it.
How this relates to arrays is that the following two lines of code are equivalent:
arr[1] = 456;
*(arr + 1) = 456;
If you're dealing with a multi-dimensional array as a single block of memory, you need to multiply the column width by the number of rows down, and then add however many columns over your data is.
Perhaps a visual will help.
Let's consider a 3x3 2-dimensional array. We'll say we've initialized it 1-9.
1 2 3
4 5 6
7 8 9
Now, we can look at this as a 3x3 array, or... we can consider it a single dimensional array with 9 elements.
1 2 3 4 5 6 7 8 9
How can we access 5?
Well, in the first case we would use something like: arr[1][1]. In the second case, we know that 5 is at index 4, so how do we turn [1][1] into [4]?
Given the pattern arr[row][col] we can multiply the row by the length of each row, and then add the col. So arr2d[1][1] turns into arr1d[1 * 3 + 1]. Lo and behold, 1 + 3 + 1 is 4.
Try this with a bigger array:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
To get the value 18 we would access: arr2d[3][2] but if this were treated as a single dimensional array: arr1d[3 * 5 + 2] which is arr1d[17] which gets us... 18.
|
69,309,112 | 69,309,162 | Make a function has higher precedence than another | So I have a function:
void foo(char a = 'A', int b = 0)
{
// code
}
And I have another one:
void foo(int b = 0, char a = 'A')
{
//code
}
Then if I call foo(), it will return an error because the compiler can't decide which function to call. So can I make a function that has higher precedence than another? So if I call foo() then the compiler which one to choose?
| You probably want to use function overloading here:
void foo(char a, int b = 0)
{
// code
}
void foo(int b, char a = 'A')
{
//code
}
void foo()
{
foo(0); // Or 'foo('A');', depends on which overload you want to give priority
}
Edit: Or you could just remove the first default argument from one of the overloads:
// Makes the compiler select the first overload when doing 'foo()'
void foo(char a = 'A', int b = 0)
{
// code
}
void foo(int b, char a = 'A')
{
//code
}
Or:
// Makes the compiler select the second overload when doing 'foo()'
void foo(char a, int b = 0)
{
// code
}
void foo(int b = 0, char a = 'A')
{
//code
}
|
69,309,225 | 69,309,299 | How to use while loops properly? | I'm a beginner in programming and here you could see that this program will get ask the user to input their grade from their first to third periodic, which will then display the average. Everything was going fine not until I get to the part where the user will be asked if he would like to average another set, when I type y(yes) it'll loop the whole thing again and again starting from the "your average grade is..". To me, I think the problem was about my bad looping. Why did that loop only that line and not the whole program? Any way I could improve my looping and programming? Is there anyway I could shorten this program?
Thanks for the time you gave answering this question.
#include <iostream>
#include <string>
using std::cout, std::cin, std::string,std::endl;
int main() {
char again{};
double P1{}, P2{}, P3{}, Grade{}, Result{};
string phrase {"Your average grade is "},
phrase1 {"Error! number should be in range of (1 to 100)."},
result1 {"Failed"},
result2 {"Study Harder"},
result3 {"Job well done"},
result4 {"Very good student"},
result5 {"Exceptional student"};
cout<<"Enter your P1 grade: ";
cin>> P1;
cout<<"Enter your P2 grade: ";
cin>> P2;
cout<<"Enter your P3 grade: ";
cin>> P3;
cout<<"\n";
while(P1 > 100 || P1 <= 0){
cout << phrase1 << endl;
cout << "Enter the Your P1 grade again: ";
cin>> P1;}
while(P2 > 100 || P2 <= 0){
cout << phrase1 << endl;
cout << "Enter the Your P2 grade again: ";
cin>> P2;}
while(P3 > 100 || P3 <= 0){
cout << phrase1 << endl;
cout << "Enter the Your P3 grade again: ";
cin>> P3;
cout<<"\n";}
do{
Result = P1 * 0.33 + P2 *0.33 + P3 *0.34;
if (Result <= 49)
cout<< phrase << Result << ", " << result1<<endl;
if (Result >= 50 && Result <= 70)
cout<< phrase << Result << ", " << result2<<endl;
if (Result >= 71 && Result <= 80)
cout<< phrase << Result << ", " << result3<<endl;
if (Result >= 81 && Result <= 90)
cout<< phrase << Result << ", " << result4<<endl;
if (Result >= 91 && Result <= 100)
cout<< phrase << Result << ", " << result5<<endl;
cout<<"Would you like to average another set?(Y/N) ";
cin>>again;
cout<<"\n";
}while(toupper(again) =='Y' );//asks if the user would like to do another set
return 0;
}
| When your while loop is triggered, it goes back to do statement and executes the program from there.
Now the problem is that the value in the do scope doesn't get updated because you are not giving input again.
The simple solution I believe is that you should move your do statement to the top.
do {
cout << "Enter your P1 grade: ";
// rest of the code here...
}
|
69,309,469 | 69,310,477 | ‘operator/’ is not a member of ‘std::filesystem’; did you mean ‘operator~' | I am trying to install the MMMTools https://mmm.humanoids.kit.edu/installation.html. My cmake version is 3.16.3. I went through every step without any errors until this section
cd ~/MMMCore
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make
The make command returns me the following error.
(base) kong@kong-Standard:~/MMMCore/build$ make
[ 1%] Building CXX object CMakeFiles/MMMCore.dir/MMM/XMLTools.cpp.o
/home/kong/MMMCore/MMM/XMLTools.cpp: In function ‘void MMM::XML::makeAbsolutePath(const string&, std::string&)’:
/home/kong/MMMCore/MMM/XMLTools.cpp:650:64: error: ‘operator/’ is not a member of ‘std::filesystem’; did you mean ‘operator~’?
650 | std::filesystem::path filenameNewComplete = std::filesystem::operator/(filenameBasePath, filenameNew);
| ^~~~~~~~~
| operator~
make[2]: *** [CMakeFiles/MMMCore.dir/build.make:76: CMakeFiles/MMMCore.dir/MMM/XMLTools.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:295: CMakeFiles/MMMCore.dir/all] Error 2
make: *** [Makefile:163: all] Error 2
But I googled the function and saw that it is a member of std::filesystem https://en.cppreference.com/w/cpp/filesystem/path/operator_slash. What went wrong?
I had a look through the CMakeLists.txt and saw this.
###########################################################
#### Compiler configuration ####
###########################################################
set(CMAKE_POSITION_INDEPENDENT_CODE ON) # enable -fPIC
if(MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /MP")
elseif(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX)
# cmake 3.10 does not understand c++2a, so we tell it we will handle the standard flag
set(CMAKE_CXX_STANDARD_DEFAULT)
add_definitions(-std=c++2a)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-long-long -pedantic")
endif()
add_compile_options(-Werror)
I am compiling it on Ubuntu 20.04 so I guess it enters the elseif section. Does it mean that it is not using C++17? Do I need to edit the line set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-long-long -pedantic") to have it use C++17?
The guide indicates that it is for 18.04 but since the issue is with C++17 I don't think the fault lies in using 20.04?
| Due to LWG 3065 the operator is now hidden and shouldn't be called directly.
std::filesystem::path filenameNewComplete = std::filesystem::operator/(filenameBasePath, filenameNew);
Should just be:
std::filesystem::path filenameNewComplete = filenameBasePath / filenameNew;
I'm guessing the code has only been tested against an older implementation (it looks like this was implemented in gcc/libstdc++ 9) than the one you are using, I don't know why it was written in such an overcomplicated way initially though.
|
69,310,015 | 69,310,087 | Single Linked List addition fault | The function to add a new list item in a single linked list
void linked_list::push(int n) {
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if (head == NULL) {
head = tmp;
tail = tmp;
}
else {
tail->next = tmp;
tail = tmp;
}
}
and for display, I used the following function code
void linked_list::display() {
if (head == NULL) {
cout << "Empty list" <<endl;
}
else {
node *tmp = head;
while (tmp->next != NULL) {
cout << tmp->data << " ";
tmp = tmp->next;
}
cout << endl;
}
}
after passing some values i.e 1 2 3 4 my expected output is all the values given but it gives the following output i.e. 1 2 3
| In order to print them all out, condition inside while has to be: while(tmp != NULL)
void linked_list::display() {
if (head == NULL) {
cout << "Empty list" << endl;
}
else {
node *tmp = head;
while (tmp != NULL) {
cout << tmp->data << " ";
tmp = tmp->next;
}
cout << endl;
}
|
69,310,441 | 69,310,463 | c++ Repeated if condition difference with bracket | I'm studying coding test with web compiler and i have an incomprehensible problem.
Does this bracket makes difference?
if(i < waitLine)
{
if(bridge.update(truck_weights[i]))
i++;
}
else
bridge.update(0);
this one is ok.
if(i < waitLine)
if(bridge.update(truck_weights[i]))
i++;
else
bridge.update(0);
but when i try this, compiler returns over time error.
what's difference of this two style? isn't that else phrase just follow with first if condition?
| This:
if(i < waitLine)
if(bridge.update(truck_weights[i]))
i++;
else
bridge.update(0);
is the same as this:
if(i < waitLine) {
if(bridge.update(truck_weights[i])) {
i++;
} else {
bridge.update(0);
}
}
Not:
if(i < waitLine)
{
if(bridge.update(truck_weights[i]))
i++;
}
else
{
bridge.update(0);
}
So, it's different; I can't say why that's a compiler error, but I'd imagine it has something to do with the surrounding code.
|
69,310,688 | 69,312,063 | strict total order of std::less<Pointer> | This question comes from this comment:
If you have say two vectors a and b, the total order is permitted to be &a[0], &b[0], &a[1], &b[1], &a[2], &b[2], ..., i.e., with the elements interleaved.
Is that order permitted?
I don't known much about the standard. That seems correct if I read only sections directly related to std::less.
And I found that Herb Sutter's gcpp library have a similar usage(link):
// Return whether p points into this page's storage and is allocated.
//
inline
bool gpage::contains(gsl::not_null<const byte*> p) const noexcept {
// Use std::less<> to compare (possibly unrelated) pointers portably
auto const cmp = std::less<>{};
auto const ext = extent();
return !cmp(p, ext.data()) && cmp(p, ext.data() + ext.size());
}
| Yes, different arrays (that are not part of the same complete object) can be interleaved in the ordering, but each array must separately be ordered correctly—this is what it means that the total order must be consistent with the partial order established by the built-in operators. The fact that a+1 points to the element immediately after *a is irrelevant to the question of unrelated arrays since the partial order is exactly that the obvious relationship between indices and pointer order pertains within one complete object. (In fact, “immediately after” is circular here, since the only observable immediacy is in the array indices themselves. Integer casts need not respect it, so you can’t see “the real addresses”.)
|
69,311,387 | 69,311,412 | Is it possible to initialize new std::vector in one line? | I just wonder if it is possible to new and initialize a std::vector at the same time, something like, do the two things in one line:
std::vector<int>* vec = new std::vector<int>(){3, 4};
instead of, first:
std::vector<int>* vec = new std::vector<int>();
then:
vec->push_back(3);
vec->puch_back(4);
|
I just wonder if is possible to new and initialize a std::vector at
the same time, something like, do the two things in one line?
Yes, you can, via std::initializer_list constructor10 of std::vector
constexpr vector( std::initializer_list<T> init,
const Allocator& alloc = Allocator() ); (since C++20)
With you can write
std::vector<int>* vec = new std::vector<int>{3, 4};
Because I need a vector that create on heap!
The terms we use in C++ are automatic and dynamic storage. In most of the cases, you do not require the std::vector<int> to be allocated dynamically, rather the elements to be there. For this, you need simply a vector of integers.
std::vector<int> vec {3, 4};
However, if you're meant for a multidimensional vector, then I will suggest having a vector of vector of inters:
std::vector<std::vector<int>> vec{ {3, 4} };
When the inner vector has the same number of length, keep a single std::vector and manipulate the indexes for acting as a two-dimensional array.
In both cases, the std::vector in the background does the memory management for you.
|
69,311,574 | 69,311,690 | CppCoreGuidlines R.33 Why pass `unique_ptr` by reference? | The CppCoreGuidlines rule R.33 suggests to
Take a unique_ptr<widget>& parameter to express that a function
reseats the widget.
Reason Using unique_ptr in this way both documents and enforces the
function call’s reseating semantics.
Note “reseat” means “making a pointer or a smart pointer refer to a
different object.”
I don't understand why we should pass by reference when reseat means "making a pointer or a smart pointer refer to a different object.”
When the function's purpose is to reseat/change the underlying object the pointer is pointing to, aren't we stealing the ownership from the caller this way and therefore should pass the unique_ptr by value, hence moving it and transferring ownership?
Is there an example that explains why passing a unique_ptr by reference is recommended?
|
When the function's purpose is to reseat/change the underlying object the pointer is pointing to, aren't we stealing the ownership from the caller this way
No. Neither when we "reseat" a pointer, nor when we change the pointed object, do we take ownership of the pointer i.e. we aren't transferring the ownership.
Is there an example that explains why passing a unique_ptr by reference is recommended?
Here is an example of a function that "reseats" a unique pointer:
void reseat(std::unique_ptr<widget>& ptr) {
ptr = std::make_unique<widget>();
}
If you tried to use a reference to const, then that wouldn't compile at all. If you tried to use a non-reference parameter, then the argument pointer wouldn't be modified and thus the behaviour wouldn't be as desired. The caller would be forced to move their pointer leaving it always null.
You could modify the example to use a pointer to unique pointer, but references are recommended because it isn't possible to pass null by mistake. A reference wrapper would also work, but it would be unnecessarily complicated.
In case we make it point somewhere else, what happens to the object it pointed before?
If a unique pointer points to something other than null, then making it point elsewhere will cause the previously pointed object to be deleted.
Aren't we leaking memory in this case?
No.
Note that the example is simple in order to be easy to understand. Typically I wouldn't recommend to write such function and instead considering to write a function that returns the new unique pointer, and let the caller "reseat" the pointer themselves. But that depends on details.
|
69,311,646 | 69,311,739 | Logic error in remove duplicates in a vector while preserving the order function | void vectorDeduplicator(std::vector<std::string>& inputVector){
for(int i = 0; i < inputVector.size() - 1; i++){
for(int x = 1; x <= inputVector.size() - 1; x++)
if(inputVector.at(i) == inputVector.at(x) && i != x){
inputVector.erase(inputVector.begin() + x);
}
}
}
Input: 1 1 2 2 4 4 3 3 1 1 3 3 3 2 2
Output: [1,2,4,1,3,2]
You can see the function I'm trying to use to remove duplicates inside of a vector. It works when duplicates are adjacent. I wouldn't like to use a faster and an efficient method without knowing anything about it that already exists within the standard library or anything else. I'd like to learn the algorithm behind it as this is for learning purposes.
| The problem is you ignore one value as you erase. You need to decrement x:
#include <vector>
#include <iostream>
void vectorDeduplicator(std::vector<int>& inputVector)
{
for(int i = 0; i < inputVector.size() - 1; i++)
{
for(int x = 1; x < inputVector.size(); x++)
{
if(inputVector.at(i) == inputVector.at(x) && i != x)
{
inputVector.erase(inputVector.begin() + x);
x--; // go one back because you erased one value
}
}
// to debug
for(const auto& x : inputVector)
std::cout << x << " ";
std::cout << std::endl;
}
}
int main(){
std::vector<int> vector{1, 1, 2, 2, 4, 4, 3, 3, 1, 1, 3, 3, 3, 2, 2};
vectorDeduplicator(vector);
// output
for(const auto& x : vector)
std::cout << x << " ";
return 0;
}
The output then is:
1 2 2 4 4 3 3 3 3 3 2 2
1 2 4 4 3 3 3 3 3
1 2 4 3 3 3 3 3
1 2 4 3
1 2 4 3
|
69,311,888 | 69,312,170 | Json nlohmann : generic function that return a value that is deep of several keys | I need a function to get the content of a value which need more than one key to access of it.
In the example bellow, I successfully get value of file_content["happy"] but how to write my function get() to accept more than one key for example access to file_content["answer"]["everything"] ?
Note that it could be more than 2 keys.
#include <nlohmann/json.hpp>
#include <string>
#include <fstream>
#include <iostream>
using json = nlohmann::json;
class My_config {
public:
My_config(const std::string config_path) {
// Open and read Configuration file
std::ifstream ifs(config_path);
if (ifs.is_open()) {
file_content = json::parse(ifs);
ifs.close();
}
}
json get(std::string key) {
return file_content[key];
}
private:
json file_content;
};
int main() {
auto my_conf = My_config("../test.json");
std::cout << "Get happy : " << my_conf.get("happy") << std::endl;
// How to get ["answer"]["everything"] ?
std::cout << "Get [answer][everything] : " << my_conf.get("answer", "everything") << std::endl;
return 0;
}
test.json :
{
"answer": {
"everything": 42
},
"happy": true
}
| Using a loop should do the job:
json get(std::initializer_list<std::string> keys) {
json data = file_content;
for (auto& key : keys) {
data = data[key];
}
return data;
}
requires extra {} at call site:
my_conf.get({"answer", "everything"});
|
69,312,288 | 69,313,044 | Access C++ signals/slots globally in all QML files | I want to access a C++ class (signals and slots) in all my qml files. When I set up a Connection in main.qml, I am able to receive the signal. However, in any other qml file (MainMenu.qml here), I can not access the signal. I can send from other qml files using slots functions, but not read the signals. Any idea how to fix it? I am very new to QML.
Main.cpp
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
Game game;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("_game", &game);
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
main.qml
Window {
id: root
width: 1240
height: 800
visible: true
title: qsTr("Horse Race")
color: "black"
Image {
id: backgroundImage
anchors.fill: parent
source: "Imgs/Background.png"
}
Loader {
id: mainLoader
anchors {
horizontalCenter: parent.horizontalCenter
verticalCenter: parent.verticalCenter
horizontalCenterOffset: - 100
}
source: "MainMenu.qml"
}
Connections {
target: _game
onNameUpdate: {
console.log("updated name")
}
onStartedNewGame: {
console.log("new game")
}
}
}
MainMenu.qml
Rectangle {
Text {
id: header
anchors.horizontalCenter: root.horizontalCenter
anchors.horizontalCenterOffset: + 35
color: "white"
font.family: "Super Mario Bros."
font.pointSize: 30
text: "Game Menu"
}
Connections {
target: _game
onStartedNewGame: {
console.log("inside MainMenu")
header.color = "blue"
}
}
}
| There are two ways that I'm aware of.
The Game class is a QObject. Instead of instantiating it in your C++ code and calling setContextProperty on the rootContext, it's better to register Game instance as a QML singleton object. You will then have access to it wherever you import it. Here is an example (TestClass will be your Game class):
#include <QQmlApplicationEngine>
#include <QCoreApplication>
#include <QDebug>
class TestClass : public QObject
{
Q_OBJECT
public:
explicit TestClass(QQmlEngine* engine, QObject *parent = nullptr);
Q_INVOKABLE void triggerSignal() { emit aSignal(); } ;
private:
QQmlEngine * m_engine;
signals:
void aSignal();
public slots:
void aSlot() { qDebug() << "aSlot invoked" };
};
static QObject *InstantiateTestClass(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(scriptEngine)
TestClass *singletonClass = new TestClass(engine);
return singletonClass;
}
static void registerTestClassSingleton()
{
qmlRegisterSingletonType<TestClass>("Globals", 1, 0, "TestClass", InstantiateTestClass);
}
Q_COREAPP_STARTUP_FUNCTION(registerTestClassSingleton)
and in every QML file you can:
...
import Globals 1.0
Item {
...
Connections {
target: TestClass
onASignal: {
console.log("A Signal triggered")
}
}
}
Be aware that the Game class will be instantiated, when you refer to it for the first time. Creating a Connection won't invoke the InstantiateTestClass function. You should either call a function on TestClass, read a property or write a property to create the singleton instance. So, it's a good idea to create TestClass instance when the Window object is created like:
//main.qml
...
Windows{
...
Component.onCompleted: {
//Just to create TestClass instance. You can also refer to a property instead of calling a method on it.
//Refering to a propery is enough for the TestClass to be instantiated.
TestClass.aSlot();
}
}
You can also create a QML singleton type, create a var property in it and then set that var to _game in your main.qml. Then you will be able to access that member from every QML file. You should create a qmldir file beside that QML singleton file.
//GameHelper.qml
pragma Singleton
...
QtObject{
property var gameInstance
}
//main.qml
...
import "."
Window{
...
Component.onCompleted: {
GameHelper.gameInstance = _game;
}
}
//MainMenu.qml
...
Item{
Connections {
target: GameHelper.gameInstance
onASignal: {
console.log("A Signal triggered")
}
}
}
Both methods will work. I will prefer the first one.
|
69,312,394 | 69,340,697 | SWIG: how to wrap a function that takes reference to int64_t as parameter? | My interface file TestRef.i:
%module test_ref
%{
#include <iostream>
%}
%include <stdint.i>
%include <typemaps.i>
%inline %{
struct Result {
uint64_t len;
void* data;
};
Result read(int64_t& idx) {
std::cout << idx << std::endl; // just to use idx
idx++;
return Result{1, nullptr};
}
void set_value(double& a) {
a = 42.;
}
%}
%apply int64_t& INOUT { int64_t& idx };
%apply double& INOUT { double& a };
void set_value(double& a);
My goal is to call read(), which returns a C struct (actually packed) and an int64_t via the reference parameter.
Here is how I built:
$ swig -python -c++ -I/usr/include TestRef.i
$ g++ -fPIC -c TestRef_wrap.cxx -I/opt/rh/rh-python38/root/usr/include/python3.8 -std=c++17 -O3
$ g++ -shared TestRef_wrap.o -o _test_ref.so -lrt
Here is the error I got:
>>> import test_ref
>>> idx = 1000
>>> p = test_ref.read(idx)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/hc/test/cpp/test_ref.py", line 79, in read
return _test_ref.read(idx)
TypeError: in method 'read', argument 1 of type 'int64_t &'
Some post suggested that reference will be "returned" and so I should do:
>>> p, idx = test_ref.read(idx)
But same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/hc/test/cpp/test_ref.py", line 79, in read
return _test_ref.read(idx)
TypeError: in method 'read', argument 1 of type 'int64_t &'
Then, I found this post.
And I tried (TestRef.i above already included set()):
>>> a = 0.0
>>> a = set_value(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/hc/test/cpp/test_ref.py", line 66, in set_value
return _test_ref.set_value(a)
TypeError: in method 'set_value', argument 1 of type 'double &'
I am using SWIG 4.0.
| According to this post, [t]he typemap must also be declared before SWIG parses test.
Changing my TestRef.i to
%module test_ref
%{
#include <iostream>
%}
%include <stdint.i>
%include <typemaps.i>
%apply int64_t& INOUT { int64_t& idx };
%apply double& INOUT { double& a };
%inline %{
struct Result {
uint64_t len;
void* data;
};
Result read(int64_t& idx) {
std::cout << idx << std::endl; // just to use idx
idx++;
return Result{1, nullptr};
}
void set(double& a) {
a = 42.;
}
works:
>>> import test_ref
>>> idx = 1024
>>> p, idx = test_ref.read(idx)
1024
>>> print(idx)
1025
>>>
|
69,312,541 | 69,312,667 | How to refactor nested for loop? | I have two similar functions. Both functions contain a nested for -loop. How I can combine these two functions to decrease duplicated code.
The only difference between funcA and funcB is funcB calls func_2 in the loop.
The two functions like below.
void funcA()
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
func_1();
}
}
}
void funcB()
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
func_1();
func_2();
}
}
}
| Perhaps I am taking it a little too far, but there is no apparent reason for the nested loops (neither func_1() nor func_2() depend on i or j). A straight forward way to pass a callable is the following:
template <typename F>
void func(F f) {
for (int i=0; i < size*size; ++i) f();
}
and then call either
func([](){ func_1(); });
func(&func_1); // passing function pointer works as well
or
func([](){ func_1(); func_2(); });
PS: There is a difference between the nested loops and the flat one when size*size can overflow or it is negative. Though passing the callable is orthogonal to that.
|
69,313,026 | 69,313,082 | Undefined Behavior when using Comma Operator in C++ | I am trying to learn how expression are evaluated in C++. So trying out and reading different examples. Below is the code about which i am unable to understand whether it will produce undefined behavior or not. The code is from here. So i guess since they have used it, this must not be UB. But i have my doubts.
#include <iostream>
int main()
{
int n = 1;
//std::cout << n << " " << ++n << std::endl;//this is undefined behavior i am sure
int m = (++n, std::cout << "n = " << n << '\n', ++n, 2*n);//will this also produce UB because here also we have cout in the same manner as above?
std::cout << "m = " << (++m, m) << '\n';
}
As you can see in the above code, i am sure that the statement:
cout << n << " " << ++n << endl;
produces undefined behavior.
My questions are:
But will the same statement used inside the comma operator produce UB(as shown in the code above)? That is, will the below given statement produce UB.
int m = (++n, std::cout << "n = " << n << '\n', ++n, 2*n);
How can we explain what is going on in terms of sequence-before, unsequenced etc the behavior of the above mentioned statement.
PS: I know since C++11 we use sequence-before etc. instead of sequence point so that why i asked the explanation in terms of current standard.
| From the same page on cppreference:
In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2 begins (note that a user-defined operator, cannot guarantee sequencing) (until C++17).
As the comma-operator in your code is the built-in one, the sequencing between ++n, std::cout << "n = " << n << '\n' and the other expressions is well defined. There is no undefined behavior.
And because you might have read already the above, here is the wording from the standard:
A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression.
The left expression is sequenced before the right expression ([intro.execution]).
|
69,313,201 | 69,313,388 | Why when I changed the value of the variable using pointer, the value was still the same? | can someone explain why the output of firstvalue is 10 although it is manipulated at the end when writing *p=20?
Code:
#include <iostream>
using namespace std;
int main(){
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;
*p2 = *p1;
p1 = p2;
*p1 = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "p1 is " << p1 << endl;
cout << "p2 is " << p2 << endl;
cout << "*p1 is " << *p1 << endl;
cout << "*p2 is " << *p2 << endl;
return 0;
}
Output:
firstvalue is 10
secondvalue is 20
p1 is 0x7ffc0589c4f4
p2 is 0x7ffc0589c4f4
*p1 is 20
*p2 is 20
| Perhaps a more "graphical" illustration might help you understand what's happening?
After the assignments
p1 = &firstvalue;
p2 = &secondvalue;
you have something which looks like this:
+----+ +------------+
| p1 | --> | firstvalue |
+----+ +------------+
+----+ +-------------+
| p2 | --> | secondvalue |
+----+ +-------------+
So when you dereference p1 then you get the value of firstvalue.
But you change things with the assignment
p1 = p2;
That makes p1 point to the same thing that p2 is pointing to, and you now have:
+----+
| p1 | --\
+----+ \ +-------------+
>--> | secondvalue |
+----+ / +-------------+
| p2 | --/
+----+
Now dereferencing p1 will give you the value of secondvalue instead.
In the future when you have problems with pointers, I suggest you take out a pencil and some paper and draw everything yourself.
Draw boxes for "things", like variables etc. Then draw arrows for pointers, from the pointer box to the thing they point to.
Then when changing a pointer, you erase the arrow and draw a new one.
|
69,313,394 | 69,313,585 | Can someone please explain me why can't return a smart pointer? | I was wondering what could be wrong with returning a smart pointer. The compiler throws that the constructor itself has been deleted. So I tried with returning the reference and it works, why is this possible?
#include <iostream>
#include <memory>
using namespace std;
using unique_int = std::unique_ptr<int>;
unique_int p_Int = std::make_unique<int>();
unique_int GetPtr()
{
return p_Int;
}
unique_int& GetPtrAddr()
{
return p_Int;
}
The error message is
function "std::unique_ptr<_Ty, _Dx>::unique_ptr(const std::unique_ptr<_Ty, _Dx>&)[with _Ty=int, Dx=std::default_delete<int>]"(declared at line 3269 of "memory library path") cannot be referenced -- it is a deleted function
| Let's examine what would happen when you return a std::unique_ptr by value.
unique_int function creates a temporary object of std::unique_ptr type, for which a copy-initialization of the temporary std::unique_ptr from p_int, which you return. But the whole point of std::unique_ptr, is that it cannot be copied, only moved.
|
69,313,574 | 69,313,680 | Converting a pointer-to-member type to a simple pointer type | I have the following type, which I get with decltype
QString UserInfo::*&
I can remove the & part by wrapping decltype with std::remove_reference_t but I also want to remove UserInfo::* part
How can I do that so I can use only QString type in my templates
I'm using this template in initializer list where I don't have access to solid object or this pointer to .* operator in decltype
| Using a valid object is not necessary in unevaluated contexts (like decltype). To exaggerate a little, you could even dereference a null pointer in there, and nothing bad would happen, since the dereference is never actually evaluated.
To create an object of a type that is not valid, but can be used in unevaluated contexts, you can use std::declval.
template<class T>
using member_type = decltype(std::declval<UserInfo>().*std::declval<T>());
|
69,313,789 | 69,412,326 | Access files generated in the backend | I'm a beginner. I started exploring Pythran and Transonic a few days back. I learned that Pythran generates a C++ file from the Python input file. I want to read those C++ generated files in the backend.
Do anyone of you have any idea about accessing files generated in the backend?
I'm implementing Pythran using Transonic's support.
Thanks!
| Have you tried running pythran with the --help option?
...
optional arguments:
-h, --help show this help message and exit
-o OUTPUT_FILE path to generated file. Honors %{ext}.
-P only run the high-level optimizer, do not compile
-E only run the translator, do not compile
...
So, the answer is: use the -E option
pythran my_python_file.py -E
|
69,313,851 | 69,313,877 | "using" keyword - passing iterator to function | I am writing a class Sequence. Its constructor takes two templated vector iterators as arguments.
Here is the code:
template <class T> using ConstIterator_t = typename std::vector<T>::const_iterator;
template <class T>
class Sequence{
public:
Sequence(ConstIterator_t start, ConstIterator_t end);
//rest of the code
};
When I compile the code it shows me this error: expected ')' before 'start'.
Could you please help me?
Many thanks in advance.
[edit] By the way, when I change ConstIterator_t with its defintion, the error disappears.
| ConstIterator_t is a template (an alias template) and you need to specify template argument for it. E.g.
template <class T> using ConstIterator_t = typename std::vector<T>::const_iterator;
template <class T>
class Sequence{
public:
Sequence(ConstIterator_t<T> start, ConstIterator_t<T> end);
// same as
Sequence(typename std::vector<T>::const_iterator start, typename std::vector<T>::const_iterator end);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.