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 |
|---|---|---|---|---|
73,055,545 | 73,055,584 | Why do some folks continue to add subsequent duplicate #include some duplicate header files in their projects? | Why do some folks continue to add subsequent duplicate #include some duplicate header files in their projects?
Bat.h
#include <SFML/Graphics.hpp>
Pong.cpp
#include "Bat.h"
#include <SFML/Graphics.hpp>
Wasn't they paying attention?
| The idea is to include the headers that the current file depends on. E.g. in Pong.cpp, you're not obliged to know whether Bat.h (which you supposedly also included) depends on <SFML/Graphics.hpp> or on another graphics library or no graphics library at all. Since double include is something we can prevent (using include guards, #pragma once), it's not a problem to list every dependency, but it's an issue to miss one.
|
73,055,625 | 73,056,546 | Deriving class with protected equality operator results in deleted default | Suppose we have the following implementation:
class A {
protected:
bool operator==(const A&) const = default;
};
class B : public A {
public:
bool operator==(const B& b) const {
return A::operator==(b);
};
};
int main() {
B x, y;
x == y;
}
This works in gcc 12.1 and clang 14.0. I also assume this to be the default behavior of B::operator==(const B& b) as the standard states:
A class can define operator== as defaulted, with a return value of bool. This will generate an equality comparison of each base class and member subobject, in their declaration order. Two objects are equal if the values of their base classes and members are equal. The test will short-circuit if an inequality is found in members or base classes earlier in declaration order.
So we can just replace the above statement with =default right? not really...
class A {
protected:
bool operator==(const A&) const = default;
};
class B : public A {
public:
bool operator==(const B& b) const = default;
};
int main() {
B x, y;
// Fails on both clang and gcc
// error: use of deleted function 'constexpr bool B::operator==(const B&) const'
// x == y;
x == y;
}
If an operator's default behavior is ill-formed, then the default behavior is to implicitly delete the function. So something about the default behavior here is ill-formed.
The only hypothesis I have is we're trying to invoke A::operator== within the context of A(maybe via std::static_cast<A>(*this) == b), which illegal because the function is protected not public. In my implementation above we're invoking A::operator== from the context of B which is legal. I don't see where in the standardese this specific behavior is specified though.
Addendum: Here's the full compiler dump of the =default implementation above:
<source>:8:10: note: 'constexpr bool B::operator==(const B&) const' is implicitly deleted because the default definition would be ill-formed:
8 | bool operator==(const B& b) const = default;
| ^~~~~~~~
<source>:8:10: error: 'bool A::operator==(const A&) const' is protected within this context
<source>:3:10: note: declared protected here
3 | bool operator==(const A&) const = default;
and I'm anticipating comments of form "why are you doing this in the first place?". The idea of removing the ability to perform == on the base class but allowing the derived classes to perform == if they so wish is a common one, but the argument for using the free function operator==(const B& lhs, const B& rhs) is valid. That's the current workaround.
| The defaulted implementation does not try to call A::operator==(b) for the base comparison.
It does something like static_cast<const A&>(*this) == static_cast<const A&>(b) instead and applies overload resolution to it as usual. This is described in [class.eq]/2 and [class.eq]/3. Also see [class.compare.default]/3 and [class.compare.default]/6 for relevant definitions.
The expression above will resolve to static_cast<const A&>(*this).operator==(static_cast<const A&>(b)). The context of the overload resolution is the class B however and therefore the special protected rule in [class.protected] applies, which forbids the type mismatch on the left hand of . and the class in which the access happens.
|
73,055,962 | 73,056,473 | C++ Dynamic Stack : typedeffing a pointer-struct? | I can't understand what's happening on the beginning of this C++ code that would explain to me how to implement a stack using Dynamic Array. I'm sure the code is correct, because the program runs correctly (correct results), but I don't understand it!
struct Node {
char Info;
Node *Link;
};
typedef Node *Stack;
Let's see:
there is a struct called Node, and it has Info and *Link as "fields", like fields on a form paper. So Node is the name of a "template" (struct) with empty "fields". Each time we use Node on this program, like, let's say, Node StackOverflow, it's like photocopying this form paper and filling it's fields;
*Link is itself another Node! But how can a pointer ("*") part of a struct be another instance of the same struct? Pointers don't have "fields" like form papers! They can only have one address as value, so only one field, like any other variable. This code doesn't makes sense;
Then *Stack is typedefined as a pointer ("*") that is a struct ("Node") that has a pointer inside ("*Link") that is really another struct ("Node *Link"). I don't understand anything anymore!!! HELP!
| Let's start with the code.
struct Node {
char Info;
Node *Link;
};
typedef Node * Stack;
And you wrote this:
there is a struct called Node, and it has Info and *Link as "fields",
like fields on a form paper. So Node is the name of a "template"
(struct) with empty "fields". Each time we use Node on this program,
like, let's say, Node StackOverflow, it's like photocopying this form
paper and filling it's fields;
That's close. You don't have a * Link, you have a Link field, which is a pointer to another node. This is an important concept called a linked list. The first item points to the second one, and that one points to the third one, et cetera. (It can also be used for so many more things).
So you can do something like this:
Node myNode;
myNode.Info = 'A';
myNode.Link = nullptr;
You now have a linked list with exactly one item, and it's Info is 'A'.
You can then do this:
Node * anotherNode = new Node();
myNode.Link = anotherNode;
anotherNode->Info = 'B';
anotherNode->Link = nullptr;
Now you have a linked list with two items, with values 'A' and 'B'.
Link is itself another Node! But how can a pointer ("") part of a struct be another instance of the same struct? Pointers don't have
"fields" like form papers! They can only have one address as value, so
only one field, like any other variable. This code doesn't makes
sense;
No. The field is called Link and it is of type Node *. That is, it's a pointer to another node.
Then Stack is typedefined as a pointer ("") that is a struct
("Node") that has a pointer inside ("*Link") that is really another
struct ("Node *Link"). I don't understand anything anymore!!! HELP!
This is the same confusion. The type is Stack and it is an alias for Node *. That is -- a Stack is a pointer to a Node object.
So these two lines of code are exactly the same:
Node * nodePtr1 = nullptr;
Stack nodePtr2 = nullptr;
Both of them define a Node * that are initialized to nullptr.
|
73,057,294 | 73,057,674 | Can programs detect if I am using ReadProcessMemory on it? | I'm writing a program to read a game's memory as it runs. I want to avoid the game noticing me however, since it might behave differently under observation. Is it possible for processes to detect the act of me inspecting it's memory from another process?
This is the method I'm using to inspect it:
// this is how I gain the target process's handle
HANDLE findHandle(const wchar * exeFilename) {
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE target = NULL;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE) {
while (Process32Next(snapshot, &entry) == TRUE) {
if (wcscmp(entry.szExeFile, exeFilename) == 0) {
target = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
break;
}
}
}
CloseHandle(snapshot);
return target;
}
// dst = destination buffer that the other process's memory is read into
// src = source address from within the other process
// hProcess = handle of the process we are inspecting
// protectedAccess = this allows us around some obstacle, though I'm not sure what/how specifically?
// returns the amount of memory read successfully
size_t patchedRead(char* dst, char* src, uint32 size, HANDLE hProcess, bool protectedAccess) {
SIZE_T readTotal = 0;
if (protectedAccess) {
DWORD oldprotect;
if(!VirtualProtectEx(hProcess, src, size, PAGE_EXECUTE_READWRITE, &oldprotect))
return 0;
ReadProcessMemory(hProcess, src, dst, size, &readTotal);
if(!VirtualProtectEx(hProcess, src, size, oldprotect, &oldprotect))
return 0;
} else {
ReadProcessMemory(hProcess, src, dst, size, &readTotal);
}
return size_t(readTotal);
}
| It's not possible to detect a ReadProcessMemory or WriteProcessMemory but it is possible to detect the preceding OpenProcess that is needed to gain access.
|
73,057,454 | 73,057,474 | Is "(unsigned)value" cast undefined behaviour? | I am writing some code to test for a bit in a bit-field and I wrote this:
return (unsigned)(m_category | category) > 0
I though this wouldn't compile, since I didn't give the integer type, but to my surprise it did. So I'm wondering, what does this do? Is it undefined?
| unsigned is the same as unsigned int.
The cast will convert the signed integer to unsigned as follows:
https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_conversions
If the destination type is unsigned, the resulting value is the smallest
unsigned value equal to the source value modulo 2n
where n is the number of bits used to represent the destination type.
That is, depending on whether the destination type is wider or narrower,
signed integers are sign-extended[footnote 1] or truncated
and unsigned integers are zero-extended or truncated respectively.
|
73,057,484 | 73,057,927 | How to compare two Blitz++ Arrays? | I am trying to compare two Blitz++ Arrays, but I am getting a compiler error saying that the expression cannot be converted into a boolean.
According to the documentation this operation should be supported.
What am I doing wrong?
Code:
#include <blitz/array.h>
int main() {
blitz::Array<double, 2> a(1, 1);
blitz::Array<double, 2> b(1, 1);
bool c = (a == b);
return 0;
}
Error:
error: cannot convert ‘blitz::BzBinaryExprResult<blitz::Equal, blitz::Array<double, 2>, blitz::Array<double, 2> >::T_result’ {aka ‘blitz::_bz_ArrayExpr<blitz::_bz_ArrayExprBinaryOp<blitz::_bz_ArrayExpr<blitz::FastArrayIterator<double, 2> >, blitz::_bz_ArrayExpr<blitz::FastArrayIterator<double, 2> >, blitz::Equal<double, double> > >’} to ‘bool’ in initialization
| blitz::Array<bool, 2> result(a == b);
or
bool c = blitz::all(blitz::Array<bool, 2>(a == b));
the conversion from expression to array is explicit.
|
73,058,455 | 73,058,474 | Why does passing functions by value work but not by reference | Here I have the code
void foo(std::function<int(int)> stuff){
//whatever
}
and it is called with
auto fct = [](int x){return 0;};
foo(fct);
Which works great. However, when I change foo to
void foo(std::function<int(int)>& stuff){ // only change is that it is passed by reference
//whatever
}
The code doesn't compile. Why is this the case? I know we can just pass the object to a reference parameter directly, we don't need the & operator like for pointers. Why can't you pass std::function types by reference?
| You are trying to bind a non-constant reference with a temporary object.
You could use a constant reference.
Here is a demonstration program.
#include <iostream>
#include <functional>
void foo( const std::function<int(int)> &stuff )
{
int x = 10;
std::cout << stuff( x ) << '\n';
}
int main()
{
auto fct = [](int x){return x * 10;};
foo(fct);
}
The program output is
100
Without the qualifier const you could write for example
#include <iostream>
#include <functional>
void foo( std::function<int(int)> &stuff )
{
int x = 10;
std::cout << stuff( x ) << '\n';
}
int main()
{
auto fct = [](int x){return x * 10;};
std::function<int(int)> f( fct );
foo(f);
}
As for the lambda-expression then according to the C++ 17 Standard (8.1.5.1 Closure types)
1 The type of a lambda-expression (which is also the type of the
closure object) is a unique, unnamed non-union class type, called the
closure type, whose properties are described below.
|
73,058,695 | 73,058,837 | How to zip vectors using template metaprogramming | I am practicing on template meta-programming and wanted to implement a simple trivial meta-function. I wonder how one can implement zip functionality on custom vectors. What I have in my mind is as follows:
Here is how the zip operation for this custom vector look like:
Inputs:
Vector<1, 2, 3>
Vector<2, 3, 4>
Vector<3, 4, 5>
Output:
Vector<6, 24, 60>
I believe my Vector class should be declared like:
template<int... vals>
struct Vector;
zip meta-function should have the signature:
template<typename... Vectors>
struct zip
{
///
}
I cannot figure out how to multiply values in the input vectors that happen to be in the same index via template meta-programming?
| You can partially specialise zip in order to expose the template parameters of the Vectors you pass.
template<typename...>
struct zip;
template<int... Us, int... Vs, typename... Tail>
struct zip<Vector<Us...>, Vector<Vs...>, Tail...> {
using type = typename zip<Vector<(Us * Vs)...>, Tail...>::type;
};
template<typename T>
struct zip<T> {
using type = T;
};
static_assert(std::is_same<zip<Vector<2, 4, 6>,
Vector<1, 2, 3>,
Vector<3, 6, 9>>::type,
/* == */ Vector<6, 48, 162>>::value);
|
73,059,358 | 73,059,460 | how to check if a string has matching values with a vector | I'm trying to use a for loop and an if statement to compare if any values in the string match with any in the vector. It only outputs "we have a match" if the first character in teststring is in the vector. Basically, it seems like the searching stops if the first character value in teststring isn't in the SpecialChars vector. Sorry if that is confusing, I can't think of a better way to explain it.
#include <iostream>
#include <vector>
void test()
{
std::vector<char> SpecialChars = {'!', '@', '#', '$', '%', '^', '&', '8', '(', ')', '-', '+', '='};
std::string teststring = "loll!@";
bool test = false;
for (int i = 0; i < SpecialChars.size(); i++)
{
if (teststring[i] == SpecialChars[i])
{
std::cout << "We have a match \n";
}
}
}
| teststring has a different length than SpcialChars, and teststring is shorter, so your for loop will go out of bounds of teststring when i reaches 6, causing undefined behavior.
You need 2 loops, one to iterate teststring, and one to iterate SpecialChars, eg:
#include <iostream>
#include <vector>
#include <string>
void test()
{
std::vector<char> SpecialChars = {'!', '@', '#', '$', '%', '^', '&', '8', '(', ')', '-', '+', '='};
std::string teststring = "loll!@";
bool found = false;
for (size_t i = 0; i < teststring.size(); ++i)
{
for (size_t j = 0; j < SpecialChars.size(); ++j)
{
if (teststring[i] == SpecialChars[j])
{
found = true;
break;
}
}
if (found) break;
}
if (found)
std::cout << "We have a match\n";
}
You can simplify the outer loop by using a range-for loop, and eliminate the inner loop by using the standard std::find() algorithm, eg:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
void test()
{
std::vector<char> SpecialChars = {'!', '@', '#', '$', '%', '^', '&', '8', '(', ')', '-', '+', '='};
std::string teststring = "loll!@";
bool found = false;
for (char ch : teststring)
{
if (std::find(SpecialChars.begin(), SpecialChars.end(), ch) != SpecialChars.end())
{
found = true;
break;
}
}
if (found)
std::cout << "We have a match\n";
}
Alternatively, you could change SpecialChars into a std::string and use std::string::find() on it, eg:
#include <iostream>
#include <string>
void test()
{
std::string SpecialChars = "!@#$%^&8()-+=";
std::string teststring = "loll!@";
bool found = false;
for (char ch : teststring)
{
if (SpecialChars.find(ch) != std::string::npos)
{
found = true;
break;
}
}
if (found)
std::cout << "We have a match\n";
}
Alternatively, you can use a lookup table, like @paddy suggested, eg:
#include <iostream>
#include <string>
#include <climits>
void test()
{
std::string SpecialChars = "!@#$%^&8()-+=";
std::string teststring = "loll!@";
bool found = false;
bool isSpecial[1 << CHAR_BIT] = {};
for(unsigned char ch : SpecialChars)
isSpecial[ch] = true;
for (unsigned char ch : teststring)
{
if (isSpecial[ch])
{
found = true;
break;
}
}
if (found)
std::cout << "We have a match\n";
}
|
73,059,564 | 73,059,592 | Using A Struct As Key For std::unordered_map | I am trying to use a struct as a key for an unordered_map. I added the 'spaceship' operator to the structure, which solved errors I was getting with normal comparisons, such as "is struct 1 greater than struct 2?", etc. However, I am getting attempting to reference a deleted function when using it as a key for my map. From what understood, adding the spaceship operator should have allowed me to use the struct as the map key. What is wrong?
struct test
{
uint32_t a;
uint32_t b;
auto operator<=>(const test&) const = default;
};
std::unordered_map<test, uint32_t> x; // Causes error
| To use a structure as a key in an unordered_map, you need two things:
A "hasher", something that will take a const test & and compute a hash, which defaults to std:hash<test>, and
A comparison predicate, which defaults to std::equal_to<test>.
You've got the second one covered with your spaceship operator, but not the first. There is no std::hash<test>.
See C++ unordered_map using a custom class type as the key for an example as how to define your own hasher.
|
73,059,585 | 73,059,646 | How do I fix my double-buffer not drawing to screen? | I'm working on a small operating system, and I ran into some screen-tearing, so I'm working on double-buffering to solve that. I'm just now running into the issue that now nothing prints to screen after revamping my rendering methods. A list of a few things that could be the issue, though I'm really not sure:
I did a lot of sketchy things to get the void dst and src to be compatible with u8 d and s in memcpy function
I implemented (or should I say copied from an external source) the double buffering bit, and there might be something I forgot to convert to the new, better system
A typo (unlikely)
Here's my C++ code:
typedef unsigned char uint8_t;
typedef unsigned char u8;
typedef unsigned short uint16_t;
typedef unsigned int u32;
typedef u32 size_t;
#define SCREEN_WIDTH 320
#define SCREEN_HEIGHT 200
#define SCREEN_SIZE (SCREEN_WIDTH * SCREEN_HEIGHT)
#define FPS 30
#define PIT_HERTZ 1193131.666
#define CLOCK_HIT (int)(PIT_HERTZ/FPS)
static uint8_t *BUFFER = (uint8_t *) 0xA0000;
// double buffers
uint8_t _sbuffers[2][SCREEN_SIZE];
uint8_t _sback = 0;
#define CURRENT (_sbuffers[_sback])
#define SWAP() (_sback = 1 - _sback)
#define screen_buffer() (_sbuffers[_sback])
#define screen_set(_p, _x, _y)\
(_sbuffers[_sback][((_y) * SCREEN_WIDTH + (_x))]=(_p))
const unsigned char font[128-32][8] = {
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0020 (space)
\*deleted to help with length and readability of code...*\
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // U+007F
};
static inline void *memcpy(void *dst, const void *src, size_t n) {
u8 *d = (u8*)(&dst);
const u8 *s = (u8*)(&src);
while (n-- > 0) {
*d++ = *s++;
}
return d;
}
void screen_swap() {
memcpy(BUFFER, &CURRENT, SCREEN_SIZE);
SWAP();
}
static inline void outb(uint16_t port, uint8_t val)
{
asm volatile ( "outb %0, %1" : : "a"(val), "Nd"(port) );
}
static inline uint8_t inb(uint16_t port)
{
uint8_t ret;
asm volatile ( "inb %1, %0"
: "=a"(ret)
: "Nd"(port) );
return ret;
}
unsigned read_pit(void) {
unsigned count = 0;
// al = channel in bits 6 and 7, remaining bits clear
outb(0x43,0b0000000);
count = inb(0x40); // Low byte
count |= inb(0x40)<<8; // High byte
return count;
}
void draw_char(char c, int x, int y, unsigned char color)
{
const unsigned char *glyph = font[(int)c-32];
for(int cy=0;cy<8;cy++){
for(int cx=0;cx<8;cx++){
if(((int)glyph[cy]&(1<<cx))==(1<<cx)){
screen_set(color,x+cx,y+cy);
}
}
}
}
void draw_string(const char * s, int x, int y, unsigned char color) {
int i = 0;
while(s[i] != false) {
draw_char(s[i],x+(i*8),y,color);
i++;
}
}
void draw_rect(int pos_x, int pos_y, int w, int h, unsigned char color) {
for(int y = 0; y<h; y++) {
for(int x = 0; x<w; x++) {
screen_set(color,x+pos_x,y+pos_y);
}
}
}
static void render() {
//draw_rect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT,0);
draw_string("Hello, reader. This is written text.", 10, 18, 15);
draw_string("If this is displayed, my code works.", 10, 10, 15);
}
extern "C" void main(){
int clock = 0;
while(true) {
clock++;
if(read_pit()!= 0 && clock == CLOCK_HIT) {
clock = 0;
render();
screen_swap();
}
}
return;
}
|
I did a lot of sketchy things to get the void dst and src to be compatible with u8 d and s in memcpy function
Yes, you did. And often that's an indication you're doing something wrong. Let's look at it:
static inline void *memcpy(void *dst, const void *src, size_t n) {
u8 *d = (u8*)(&dst);
const u8 *s = (const u8*)(&src);
while (n-- > 0) {
*d++ = *s++;
}
return d;
}
Here, you take the address of your pointer variables (instead of the pointer value itself). So that's a void**, which you then cast to a u8*. When you dereference that, you are then looking at individual bytes of the memory that holds this pointer. That's clearly incorrect.
Another thing that's weird is your function returns the value of d+n. This is not how the standard memcpy function works. It will always return dst. So, consider doing that if you really want to have a function with standard behavior.
This is what you should have done:
static inline void *memcpy(void *dst, const void *src, size_t n)
{
u8 *d = (u8*)dst;
const u8 *s = (const u8*)src;
while (n-- > 0) {
*d++ = *s++;
}
return dst;
}
You're also invoking it strangely:
memcpy(BUFFER, &CURRENT, SCREEN_SIZE);
Now, technically &CURRENT works okay because your CURRENT macro points to an array. But taking the address of an array is something you should avoid. Let the compiler convert the array to a pointer for you:
memcpy(BUFFER, CURRENT, SCREEN_SIZE);
Here's an alternative implementation that avoids decrementing n every loop:
static inline void *memcpy(void *dst, const void *src, size_t n)
{
u8 *d = (u8*)dst;
const u8 *s = (const u8*)src;
const u8 *s_end = s + n;
while (s != s_end) {
*d++ = *s++;
}
return dst;
}
If you're using a C compiler, also consider also adding restrict keywords because src and dst do not overlap.
|
73,059,808 | 73,059,891 | Why can my comment consist of so much forward slash (/)? | I know that there are many types of comment, I will list out a few of them (those related):
// - Normal comment
/// - This would make the comment bold
And surprisingly, the IDE would not raise an error in this code (Even it is not executed, it should still control the programmer somewhere):
/////////////////// HI!
Why would the standard allow this to happen?
BTW, my IDE is Code::Blocks 20.03 if it matters.
| As per the C++ standard: lex.comment
The characters // start a comment, which terminates immediately before the next new-line character.
From the above, you can infer that every character (other than newline) which follows the first two / characters is part of the comment.
If that wasn't already clear enough, it goes on to note:
The comment characters //, /*, and */ have no special meaning within a // comment and are treated just like other characters.
|
73,060,094 | 73,060,177 | For loop in c++ is not running while using this way: for(int i=-1;i<vector.size();i++) cout << i << endl; | I have a particular use case where I have to initialize i value in for loop to -1 and write the exiting condition based on vector size. But the problem is the loop is not getting executed at all.
This is the code.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> vec = { 1, 2, 3, 4, 5 };
for(int i=-1;i<vec.size();i++) cout << i << " ";
return 0;
}
But I am able to do like this.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> vec = { 1, 2, 3, 4, 5 };
int size = vec.size();
for(int i=-1;i<size;i++) cout << i << " ";
return 0;
}
Can anyone explain this weird behavior or am I doing something wrong there?
| i<size() in the first snippet compares a signed int i; to an unsigned size_t size; (size_t is the typical typedef for vector::size_type)
When the compiler sees that comparison, it converts the int to an unsigned value. Typically something like 2^64 - 1, for your first value of -1. This value is much bigger than 5, so the loop doesn't run.
Take-away: Don't compare signed and unsigned value with less-than or greater-than.
In fact, in a modern world you can compare signed and unsigned using std::cmp_less https://en.cppreference.com/w/cpp/utility/intcmp
|
73,060,302 | 73,060,451 | std::invocable seems to be acting differently on functors within structs | Consider the following code:
#include <concepts>
#include <functional>
struct A {
auto operator()(int const &) const noexcept {
return 0;
}
};
static_assert(std::invocable<A const &, int const &>);
struct X {
struct B {
auto operator()(int const &) const noexcept {
return 0;
}
};
static_assert(!std::invocable<B const &, int const &>); // Why?
};
static_assert(!std::invocable<X::B const &, int const &>); // Why?
void foo()
{
int x = 1;
A a;
X::B b;
std::invoke(a, x);
std::invoke(b, x);
}
On godbolt.org: https://godbolt.org/z/eT857zfrb
Results seem consistent between gcc, clang, and MSVC. Why does std::invocable fail on the sub-struct? The function foo seems to show that they are both "invocable".
| At the point where you write static_assert(!std::invocable<B const &, int const &>);, within X, X is not yet a complete type. As cppreference states
If an instantiation of a template [in the std::is_invocable family] depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.
In this case, you are depending on the incomplete type X. (I'm sure the standard has a more detailed explanation.) std::invocable is defined in terms of a requires clause using std::invoke (at least, according to cppreference; GCC appears to use std::is_invocable directly), and std::invoke is defined to depend on std::is_invocable (though again, it appears this is not exactly the case in the implementations), so this static_assert is actually causing UB (hence the implementations aren't wrong for their odd behavior.)
If you remove the static_assert within X, then the UB is removed and an assertion outside X will start having the correct behavior.
struct X {
struct B {
auto operator()(int const &) const noexcept {
return 0;
}
};
// UB!: static_assert(!std::invocable<B const &, int const &>);
};
static_assert(std::invocable<X::B const &, int const &>); // passes
|
73,061,125 | 73,061,274 | In has-a relation is it a good design, to access and alter the private members of contained class directly from the Parent class method | Consider this example:
class Child
{
private:
string m_Name;
public:
string* GetNameAccess()
{
return &m_Name;
}
};
class Parent
{
private:
Child m_Child;
public:
void DoSomething()
{
string *pChildName = m_Child.GetNameAccess(); // Is this the right thing to do?
*pChildName = "NewName";
}
};
In has-relation we know that Parent object owns the child object (i.e controls the lifetime of child).
So is Parent allowed to directly access the private members of child and alter them ?
| Although having a public function that returns a pointer to a private data member is legal in C++, it breaks the whole point of encapsulation. As mentioned in the comments, if you want to provide such 'direct' access to the data member, then just make it public.
But there are many good reasons why a data member should be private – such as offering some control(s) over what values are allowed or disallowed for that member. In such circumstances, you should provide genuine 'getter' and 'setter' functions to allow controlled access to that private member from outside the class. The 'getter' should not allow modification of the data (so returning a const& reference is generally appropriate) and the 'setter' should perform the required checks on the value it is given, before making a modification to the data.
Here is a very brief outline of how such a 'getter' and 'setter' may look for your example:
#include <string>
class Child {
private:
std::string m_Name;
public:
const std::string& GetName() { // The "const" prevents modification with the getter
return m_Name;
}
void SetName(const std::string& name) {
// A real setter allows error checking ...
if (name != "Attila the Hun") m_Name = name;
}
};
class Parent {
private:
Child m_Child;
public:
void DoSomething() {
std::string temp = m_Child.GetName();
if (temp.empty()) temp = "New Name";
else temp += " (Modified)";
m_Child.SetName(temp);
}
};
This short snippet demonstrates how you could prevent a parent naming their child, "Attila the Hun," which is perhaps a reasonable precaution for a setter function to implement.
|
73,061,333 | 73,063,096 | How can a class have a function implementation but without its declaration? | I am reading the following source code (taken from this repository).
void AVariableReplicationCharacter::GetLifetimeReplicatedProps(TArray< FLifetimeProperty >& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
// Variable A doesn't have any additional replication condition
DOREPLIFETIME(AVariableReplicationCharacter, A);
// Variable B should only replicate to the owner of this actor
DOREPLIFETIME_CONDITION(AVariableReplicationCharacter, B, COND_OwnerOnly);
}
The function is implemented in .cpp but it has not corresponding declaration in .h. Surprisingly it can be compiled.
I attempted to replicate it with a simpler one as follows but it does not compile.
#include <iostream>
using namespace std;
class Parent
{
public:
virtual void Job() const;
};
void Parent::Job() const
{
cout << "Parent" << endl;
}
class Child : public Parent
{
public:
virtual void Job() const override;
};
void Child::Job() const
{
Parent::Job();
cout << "Child" << endl;
}
class GrandChild : public Child
{
};
//= ATTEMPTING TO IMPLEMENT WITHOUT DECLARATION
void GrandChild::Job() const
{
Child::Job();
}
int main()
{
std::cout << "Hello World!\n";
std::getchar();
}
Question
What C++ concept am I missing here?
| There is already an accepted answer to this question, but it's vague and based on guessing, so I'll try to give a more definitive answer:
When declaring a class that can be replicated, it has to be defined as either an AActor or a UActorComponent. Both of which use the UCLASS() macro to denote that the following class declaration needs to be integrated into Unreals reflection using the Unreal Header Tool (UHT) which runs before the actual build and generates code. This code is written into a generated header file called "foo.generated.h" and code file called "foo.gen.cpp" where "foo" stands for your header filename (without extension). The header is always the last include in your header and exists once per header file, not per class.
Inside of the class, you also have to call the GENERATED_BODY() macro (or alternatively the GENERATED_UCLASS_BODY() macro, but I believe that's legacy stuff). That's where the code goes that's generated for the class itself by the UHT. It contains information about the UPROPERTY() and UFUNCTION() declarations and, if you are using the reflection on the class, also declares an override of GetLifetimeReplicatedProps() that you then have to implement.
This is not the only method that is declared by the UHT. If you are using RPCs, you also have to create an implementation to something you did not actually declare. A method declared as Foo() will have Foo_Implementation() as a body (because the implementation of the actual Foo() will be created via UHT, calling your implementation at some point) and optionally even a Foo_Validate().
You can read more about this here.
Regarding the UHT, Unreals docs are very vague, but I encourage you to look into its code on their GitHub. Also, you can actually "go to declaration" of GetLifetimeReplicatedProps() after doing a compile. You should be able to view the generated code in the headers, they are located in the "Intermediate/Build" folders of your project.
|
73,061,555 | 73,097,510 | Given perpendicular distance d on line1, how to find point P on line2 in C++? | Given line1, line2, and distance d, I want to write a program to calculate the point on Line2 that is perpendicular to Line1, and the perpendicular distance is d.
Does anyone know where to start?
In C++ or any other programming language.
Thanks in advance.
| Normalize line1 equation
L = sqrt(a1*a1+b1*b1)
a11 = a1 / L
b11 = b1 / L
c11 = c1 / L
Now for arbitrary point (x,y) length of perpendicular projection onto line1 is
d = a11*x + b11*y + c11
a11*x + b11*y + (c11-d) = 0
for vertical line2 case (b2==0) and (b11 != 0)
x = c2/a2
a11*c2/a2 + b11*y + (c11-d) = 0
y = -(a11*c2/a2 + (c11-d)) / b11
so needed point is (c2/a2, -(a11*c2/a2 + (c11-d)) / b11)
For general case, if (a11*b2 != b11*a2) (non-parallel line case):
y = - (a2*x + c2)/b2
a11*x - b11*(a2*x+c2)/b2 + (c11-d) = 0
a11*x - b11*a2*x/b2 + (c11 - d - b11*c2/b2) = 0
x*(a11 - b11*a2/b2) = (d + b11*c2/b2 - c11)
x = (d + b11*c2/b2 - c11) / (a11 - b11*a2/b2)
and point is ((d + b11*c2/b2 - c11) / (a11 - b11*a2/b2), y for this x)
|
73,062,967 | 73,062,999 | How should I assume which iterator category an algorithm uses? | Let's say :
std::sort(beg1, beg2, pred);
This algorithm takes a range of iterators for the container and a predicate. It takes an LegacyRandomAccessIterator.
I do understand the the 5 iterator categories are categorised by their operators.
Albeit I'm having a hard time assuming which iterator the algorithm uses.
| There is no need to assume anything, it is all documented. According to cppreference the iterators are LegacyRandomAccessIterator.
Type requirements
-RandomIt must meet the requirements of ValueSwappable and LegacyRandomAccessIterator.
-The type of dereferenced RandomIt must meet the requirements of MoveAssignable and MoveConstructible.
The page for LegacyRandomAccessIterator describes what such an iterator looks like.
|
73,063,320 | 73,063,374 | Is it bad to store the underlying type of an object? | If I have a class called Node, would it be bad, if objects of the Node class knew their NodeType, and the NodeType would be used to cast to a specific interface like this:
// NodeType
enum class NodeType : uint8_t
{
None = 0,
Foo = 1 << 0,
Bar = 1 << 1,
FooBar = 1 << 2,
FooMask = Foo | FooBar,
BarMask = Bar | FooBar,
};
inline constexpr uint8_t operator&(const NodeType& t_lhs, const NodeType& t_rhs)
{
return static_cast<uint8_t>(t_lhs) & static_cast<uint8_t>(t_rhs);
}
// Base Node Class
class Node
{
public:
virtual NodeType GetNodeType() const = 0;
};
// Interfaces
class IFoo
{
public:
virtual ~IFoo() = default;
virtual void FooSpecificMethod() const = 0;
};
class IBar
{
public:
virtual ~IBar() = default;
virtual void BarSpecificMethod() const = 0;
};
// Derived Node Classes
class FooNode : public Node, public IFoo
{
public:
NodeType GetNodeType() const override { return NodeType::Foo; }
void FooSpecificMethod() const override { std::cout << "Foo.\n"; }
};
class BarNode : public Node, public IBar
{
public:
NodeType GetNodeType() const override { return NodeType::Bar; }
void BarSpecificMethod() const override { std::cout << "Bar.\n"; }
};
class FooBarNode : public Node, public IFoo, public IBar
{
public:
NodeType GetNodeType() const override { return NodeType::FooBar; }
void FooSpecificMethod() const override { std::cout << "Foo.\n"; }
void BarSpecificMethod() const override { std::cout << "Bar.\n"; }
};
// Use of NodeType and Interfaces
std::vector<std::unique_ptr<Node>> GetNodes()
{
std::vector<std::unique_ptr<Node>> nodes{};
nodes.push_back(std::make_unique<FooNode>());
nodes.push_back(std::make_unique<FooNode>());
nodes.push_back(std::make_unique<BarNode>());
nodes.push_back(std::make_unique<FooBarNode>());
nodes.push_back(std::make_unique<FooBarNode>());
nodes.push_back(std::make_unique<FooBarNode>());
return nodes;
}
int main()
{
std::vector<std::unique_ptr<Node>> nodes{ GetNodes() };
for (const auto& node : nodes)
{
if ((node->GetNodeType() & NodeType::FooMask) != 0)
dynamic_cast<const IFoo*>(node.get())->FooSpecificMethod();
}
for (const auto& node : nodes)
{
if ((node->GetNodeType() & NodeType::BarMask) != 0)
dynamic_cast<const IBar*>(node.get())->BarSpecificMethod();
}
}
My goal is to do type specific things on objects in a polymorphic collection like in the last code snippet. Is this a bad approach? Is there any more OO approach to this?
|
Is this a bad approach? Is there any more OO approach to this?
Yes. You can just dynamic_cast to the appropriate pointer type and check the result is not null.
int main()
{
std::vector<std::unique_ptr<Node>> nodes{ GetNodes() };
for (const auto& node : nodes)
{
if (auto foo = dynamic_cast<const IFoo*>(node.get()))
foo->FooSpecificMethod();
}
for (const auto& node : nodes)
{
if (auto bar = dynamic_cast<const IBar*>(node.get()))
bar->BarSpecificMethod();
}
}
If for some reason you want to avoid dynamic_cast, you can add virtual functions to Node. This is perhaps the "most OO" way.
class Node
{
public:
virtual ~Node() = default;
virtual const IFoo * asFoo() const { return nullptr; }
virtual const IBar * asBar() const { return nullptr; }
};
class FooNode : public Node, public IFoo
{
public:
const IFoo* asFoo() const override { return this; }
void FooSpecificMethod() const override { std::cout << "Foo.\n"; }
};
class BarNode : public Node, public IBar
{
public:
const IBar* asBar() const override { return this; }
void BarSpecificMethod() const override { std::cout << "Bar.\n"; }
};
class FooBarNode : public Node, public IFoo, public IBar
{
public:
const IFoo* asFoo() const override { return this; }
const IBar* asBar() const override { return this; }
void FooSpecificMethod() const override { std::cout << "Foo.\n"; }
void BarSpecificMethod() const override { std::cout << "Bar.\n"; }
};
int main()
{
std::vector<std::unique_ptr<Node>> nodes{ GetNodes() };
for (const auto& node : nodes)
{
if (auto foo = node->asFoo())
foo->FooSpecificMethod();
}
for (const auto& node : nodes)
{
if (auto bar = node->asBar())
bar->BarSpecificMethod();
}
}
|
73,063,464 | 73,065,011 | Function accepting a reference to std::variant | I'm trying to pass values to a function accepting a std::variant.
I noticed I can use a function accepting a const reference to a variant value, but not a reference alone. Consider this code
#include <variant>
#include <queue>
#include <iostream>
struct Foo{ std::string msg{"foo"}; };
struct Bar{ std::string msg{"bar"}; };
using FooBar = std::variant<Foo,Bar>;
void f1(const FooBar&)
{
std::cout << "yay" << std::endl;
}
void f2(FooBar&)
{
std::cout << "wow" << std::endl;
}
int main()
{
Foo f;
Bar b;
f1(f); // fine
f1(b); // fine
f2(f); // compile error
}
gives me error
invalid initialization of reference of type 'FooBar&' {aka 'std::variant<Foo, Bar>&'} from expression of type 'Foo'
42 | f2(f);
so the first question is: why is that prohibited?
I can't figure out.
Why I'm doing this?
I'm trying to use two accessor function to read and modify the values using std::visit, something like this:
#include <variant>
#include <queue>
#include <iostream>
struct Foo{ std::string msg{"foo"}; };
struct Bar{ std::string msg{"bar"}; };
using FooBar = std::variant<Foo,Bar>;
std::string f3(const FooBar& fb)
{
return std::visit([](auto& foobar){
std::string ret = "yay ";
return ret + foobar.msg;
}, fb);
}
void f4(FooBar& fb)
{
std::visit([](auto& foobar){
foobar.msg += "doo";
}, fb);
}
int main()
{
Foo f;
Bar b;
std:: cout << f3(f) << " " << f3(b); // fine
f4(f); // does not compile
}
which of course does not compile with
error: cannot bind non-const lvalue reference of type 'FooBar&' {aka 'std::variant<Foo, Bar>&'} to an rvalue of type 'FooBar' {aka 'std::variant<Foo, Bar>'}
44 | f4(f);
| ^
So second question: how can I achieve this behaviour?
| You cannot pass a temporary resulting from converting the Foo to a std::variant<Foo,Bar> to f2. C++ disallows this because binding a temporary to a non-const reference is most likely a bug. If it was possible you'd have no way to inspect the modified value anyhow.
You can workaround this by using a std::variant of references (actually std::reference_wrapper) and pass that by value. You'd then use two overloads, one for non-const and one for const references, in both cases the temporary std::variant can be passed by value while modifications inside the function are made directly on the object used to construct the std::variant:
#include <variant>
#include <queue>
#include <iostream>
#include <functional>
struct Foo{ std::string msg{"foo"}; };
struct Bar{ std::string msg{"bar"}; };
using FooBar = std::variant<std::reference_wrapper<Foo>,std::reference_wrapper<Bar>>;
using ConstFoobar = std::variant<std::reference_wrapper<const Foo>,std::reference_wrapper<const Bar>>;
void f1(ConstFoobar)
{
std::cout << "yay" << std::endl;
}
void f2(FooBar)
{
std::cout << "wow" << std::endl;
}
int main()
{
Foo f;
Bar b;
f1(f); // yay
f1(b); // yay
f2(f); // wow
}
Complete Example
PS: The simpler solution is of course to have two overloads taking plain Foo and Bar (ie for each a non and a const reference overload, makes 4 in total). Though I suppose you are using std::variant for some other reasons not directly apparent from the example code.
|
73,063,544 | 73,068,361 | How to add expectations alongside with ASSERT_DEATH in GoogleTest for C++ | Given those interfaces:
class ITemperature
{
public:
virtual ~ITemperature() = deafult;
virtual int get_temp() const = 0;
};
class IHumidity
{
public:
virtual ~IHumidity() = deafult;
virtual int get_humidity() const = 0;
};
And this SUT:
class SoftwareUnderTest
{
public:
SoftwareUnderTest(std::unique_ptr<ITemperature> p_temp,
std::unique_ptr<IHumidity> p_humidity)
: m_temp{std::move(p_temp)}, m_humidity{std::move(p_humidity)}
{}
bool checker()
{
assert(m_temp && "No temperature!");
if (m_temp->get_temp() < 50)
{
return true;
}
assert(m_humidity && "No humidity");
if (m_humidity->get_humidity() < 50)
{
return true;
}
return false;
}
private:
std::unique_ptr<ITemperature> m_temp;
std::unique_ptr<IHumidity> m_humidity;
};
And this mocks:
class MockITemperature : public ITemperature
{
public:
MOCK_METHOD(int, get_temp, (), (const override));
};
class MockIHumidity : public IHumidity
{
public:
MOCK_METHOD(int, get_humidity, (), (const override));
};
I want to make a test that checks that get_temp is called and also that the second assert (the one that checks that the humidity is nullptr), but when a do this test, I get the assert, but I the expectation tells me that it's never called (but it is actually called once)
this is the test:
class Fixture : pu`blic testing::Test
{
protected:
void SetUp() override
{
m_sut = std::make_unique<SoftwareUnderTest>(m_mock_temperature, m_mock_humidity);
}
std::unique_ptr<StrickMockOf<MockITemperature>> m_mock_temperature = std::make_shared<StrickMockOf<MockITemperature>>();
std::unique_ptr<StrickMockOf<MockIHumidity>> m_mock_humidity;
std::unique_ptr<SoftwareUnderTest> m_sut;
};
TEST_F(Fixture, GIVEN_AnInvalidHumidityInjection_THEN_TestMustDie)
{
EXPECT_CALL(*m_mock_temperature, get_temp).Times(1);
ASSERT_DEATH(m_sut->checker(), "No humidity");
}
| Apparently, this is a known limitation, see here and here.
From what I have managed to discover by experimentation so far:
If you can live with the error message about leaking mocks (haven't checked if it's true or a false positive, suppressing it by AllowLeak triggers the actual crash), it can be done by making the mocks outlive the test suite and then wrapping references/pointers to them in one more interface implementation.
//mocks and SUT as they were
namespace
{
std::unique_ptr<testing::StrictMock<MockIHumidity>> mock_humidity;
std::unique_ptr<testing::StrictMock<MockITemperature>> mock_temperature;
}
struct MockITemperatureWrapper : MockITemperature
{
MockITemperatureWrapper(MockITemperature* ptr_) : ptr{ptr_} {assert(ptr);}
int get_temp() const override { return ptr->get_temp(); }
MockITemperature* ptr;
};
struct Fixture : testing::Test
{
void SetUp() override
{
mock_temperature
= std::make_unique<testing::StrictMock<MockITemperature>>();
m_mock_temperature = mock_temperature.get();
// testing::Mock::AllowLeak(m_mock_temperature);
m_sut = std::make_unique<SoftwareUnderTest>(
std::make_unique<MockITemperatureWrapper>(m_mock_temperature), nullptr);
}
testing::StrictMock<MockITemperature>* m_mock_temperature;
std::unique_ptr<SoftwareUnderTest> m_sut;
};
TEST_F(Fixture, GIVEN_AnInvalidHumidityInjection_THEN_TestMustDie)
{
EXPECT_CALL(*m_mock_temperature, get_temp).WillOnce(testing::Return(60));
ASSERT_DEATH(m_sut->checker(), "No humidity");
}
https://godbolt.org/z/vKnP7TsrW
Another option would be passing a lambda containing the whole to ASSERT_DEATH:
TEST_F(Fixture, GIVEN_AnInvalidHumidityInjection_THEN_TestMustDie)
{
ASSERT_DEATH(
[this] {
EXPECT_CALL(*m_mock_temperature, get_temp)
.WillOnce(testing::Return(60));
m_sut->checker();
}(), "No humidity");
}
Works, but looks ugly, see here.
Last but not least: one can use custom assert or replace__assert_failed function and throw from it (possibly some custom exception), then use ASSERT_THROW instead of ASSERT_DEATH. While I'm not sure replacing __assert_failed is legal standard-wise (probably not), it works in practice:
struct AssertFailed : std::runtime_error
{
using runtime_error::runtime_error;
};
void __assert_fail(
const char* expr,
const char *filename,
unsigned int line,
const char *assert_func )
{
std::stringstream conv;
conv << expr << ' ' << filename << ' ' << line << ' ' << assert_func;
throw AssertFailed(conv.str());
}
Example: https://godbolt.org/z/Tszv6Echj
|
73,064,491 | 73,064,563 | Trouble with pointer to templated class method | I was writing code for the following parallel processing task:
A std::vector<T> contains data items that need to be processed
A function process_data<T&> does that processing on such a single data item
In my software I want to do this for different types T, so I wrote a template class:
#include <mutex>
#include <thread>
#include <vector>
// Parallel processing class.
template <class T>
class parallel_processing {
public:
// Do parallel processing for all items in the vector.
void do_parallel_processing(std::vector<T>& items,
void (*item_processor)(T&),
size_t thread_count = 1)
{
// Check if we should do sequential processing after all.
if (thread_count <= 1) {
for (size_t i = 0; i < items.size(); i++)
item_processor(items[i]);
return;
}
// Proceed with parallel processing.
item_processor_ptr = item_processor;
items_ptr = &items;
next_item_index = 0;
// Spawn all threads.
std::vector<std::thread> threads;
for (size_t i = 0; i < thread_count; i++)
threads.push_back(std::thread(item_thread_worker));
// The current thread should also work hard. This has an advantage: calling join()
// (see below) blocks the thread, costing time. Method 'item_thread_worker' however
// only returns if all items are processed and thus all threads must also have
// finished (or are busy with their last item...).
item_thread_worker();
// Wait for all threads to finish and call join on them.
for (auto& this_thread : threads)
this_thread.join();
}
private:
// Get the next index to process.
int get_next_item_index()
{
const std::lock_guard<std::mutex> lock(next_item_index_mutex);
// Check if we're already done.
if (next_item_index >= (int)items_ptr->size())
return -1;
// Next index (first return, then increment).
return next_item_index++;
}
// Thread-worker method for items.
void item_thread_worker()
{
int item_index;
// Keep on processing while not all items are processed.
while ((item_index = get_next_item_index()) >= 0)
item_processor_ptr((*items_ptr)[item_index]);
}
// Properties.
std::mutex next_item_index_mutex; // For thread-safe access to 'next_item_index'.
int next_item_index; // Identifies the next item index to process.
void (*item_processor_ptr)(T& items); // The item processing function.
std::vector<T>* items_ptr; // Pointer to the vector with items to be processed.
};
The idea is simple and worked when it was not yet in a template class but separate functions but then of course could only be coded for a single type T:
A number of threads is started and they all run the same worker method
The workers pick a data item to be processed from the std::vector<T>, and call the function to process the selected item until all items are processed
The compiler (VS2019) complains about the line:
threads.push_back(std::thread(item_thread_worker));
'use & to create a pointer to a member'
So I tried threads.push_back(std::thread(&item_thread_worker)); which gives me the error:
''&': illegal operation on bound member function expression'
So I tried all kind of things: with (), with the class in front ¶llel_processing<T>:: or ¶llel_processing:: but all I get are different errors...
My knowledge about C++ is clearly not enough to solve this, help is appreciated.
| As item_thread_worker is a non-static member function, it needs a object to be called with.
When you create your threads, you don't specify any objects. Those objects (which becomes the this pointer inside the functions) are passed as a hidden "first" argument.
Another point is that to get a pointer to a member function, you must use the pointer-to operator &. Unlike non-member functions, member functions do not decay to pointers to themselves. And you need to use the full scope, with the class-name.
So to create a thread using a non-static member function, that should be called on this object, you need to do std::thread(¶llel_processing::item_thread_worker, this).
|
73,065,507 | 73,065,572 | Implemtation of += operator oveloaded for the Class Vector. C++ | I need to implement the overloading of the += operator in c++. I have a Vector class and my implentation of += needs to add an integer from the back of my Vector.
For example: if my vector V1 contains of {1, 2, 3} and I write V1 += 4, it needs to give me {1, 2, 3, 4}.
I have almost the same functionality with the overload of the + operator which receives a Vector and an int and adds the given integer to the back of the array.
Fields for my class
class Vector
{
unsigned int _size;
int * _list;
HERE IS MY NON-WORKING SOLUTION FOR += OPERATOR
Vector& operator+=(const int val)
{
Vector temp;
temp._list = new int[_size + 1];
temp._size = this->_size + 1;
for (unsigned int i = 0; i < temp._size; i++)
{
if (i < temp._size - 1)
{
temp._list[i] = this->_list[i];
}
else if (i == temp._size - 1)
{
temp._list[i] = val;
}
}
return temp;
}
AND ALMOST IDENTICAL WORKING SOLUTION FOR + OPERATOR
friend Vector operator+(Vector lhs, const int val)
{
Vector temp;
temp._list = new int[lhs._size + 1];
temp._size = lhs._size + 1;
for (unsigned int i = 0; i < temp._size; i++)
{
if (i < temp._size - 1)
{
temp._list[i] = lhs._list[i];
}
else if (i == temp._size - 1)
{
temp._list[i] = val;
}
}
return temp;
}
I can't understand where is the key difference, however I am guessing it is somewhere in & or friend concepts, cuz I dont'really understand how they are working in this case.
And one more thing I MUST NOT CHANGE THE DESCRIPTION OF MY METHODS. (just the implementation)
| In the += operator, you should set the new value to the vecor to be added itself.
Also note that returning a reference to a non-static local variable temp is a bad idea.
Try this:
Vector& operator+=(const int val)
{
Vector temp;
temp._list = new int[_size + 1];
temp._size = this->_size + 1;
for (unsigned int i = 0; i < temp._size; i++)
{
if (i < temp._size - 1)
{
temp._list[i] = this->_list[i];
}
else if (i == temp._size - 1)
{
temp._list[i] = val;
}
}
// move the data in temp to this object
this->_size = temp._size;
delete[] this->_list;
this->_list = temp._list;
// assign new array to temp for being destructed
temp._list = new int[1];
temp._size = 1;
// return a reference to this object
return *this;
}
|
73,065,915 | 73,067,958 | How to test several interface implementations with different constructors with gtest in C++? | I have an interface for which I have three implementations. I am using the TYPED_TEST from google test so that I can use the same set of tests for all implementations. I have the following Fixture.
template <typename T>
class GenericTester : public ::testing::Test {
protected:
T test_class;
};
I added the implementation types below.
using TestTypes = ::testing::Types<ImplementationOne, ImplementationTwo>
TYPED_TEST_SUITE(GenericDiffTester, DiffTypes);
So far, everything works fine, but now I have added another implementation. The difference between the last implementation is that its constructor requires taking a std::string as an argument, whereas the first two can be default constructed.
Now when I add this third interface, it does not compile.
using TestTypes = ::testing::Types<ImplementationOne, ImplementationTwo, ImplementationThree>
TYPED_TEST_SUITE(GenericDiffTester, DiffTypes);
Obviously, the problem is that the fixture requires test_class to be default constructible, which does not apply to ImplementationThree.
How can I initialize the templated member variable of a class depending on the provided type T? I want to default construct test_class if T is of type ImplementationOne or ImplementationTwo. Otherwise, I want to construct it as ImplementationThree with a string.
Is there a way to do it directly with Gtest without a hacky solution?
| The easiest way is to derive from your non-default constructible class. That derived class could be default constructible:
class TestableImplementationThree : public ImplementationThree
{
public:
TestableImplementationThree() :
ImplementationThree("dummy")
{}
};
And:
using TestTypes = ::testing::Types<
ImplementationOne,
ImplementationTwo,
TestableImplementationThree>;
If you like to test ImplementationThree with different constructor argument - then just create and test as many testable-classes as needed.
if you do insist on testing exactly ImplementationThree - then wrap all classes with some kind of holders. For ImplementationThree specialize its "holder" to construct it differently.
template <typename T>
struct Holder
{
T tested_object;
};
template <>
struct Holder<ImplementationThree>
{
ImplementationThree tested_object{"dummy"};
};
template <typename T>
class GenericTester : public ::testing::Test,
protected Holder<T>
{
};
|
73,067,159 | 73,067,616 | Set all meaningful unset bits of a number | Given an integer n(1≤n≤1018). I need to make all the unset bits in this number as set (i.e. only the bits meaningful for the number, not the padding bits required to fit in an unsigned long long).
My approach: Let the most significant bit be at the position p, then n with all set bits will be 2p+1-1.
My all test cases matched except the one shown below.
Input
288230376151711743
My output
576460752303423487
Expected output
288230376151711743
Code
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main() {
ll n;
cin >> n;
ll x = log2(n) + 1;
cout << (1ULL << x) - 1;
return 0;
}
| If you need to do integer arithmetics and count bits, you'd better count them properly, and avoid introducing floating point uncertainty:
unsigned x=0;
for (;n;x++)
n>>=1;
...
(demo)
The good news is that for n<=1E18, x will never reach the number of bits in an unsigned long long. So the rest of you code is not at risk of being UB and you could stick to your minus 1 approach, (although it might in theory not be portable for C++ before C++20) ;-)
Btw, here are more ways to efficiently find the most significant bit, and the simple log2() is not among them.
|
73,067,913 | 73,074,249 | QStringList creation in place for parameter passing | I have a function that gets a QStringList as a parameter.
The QStringList is created in place for parameter passing. Two possibilities come to my mind for this:
myFunction(QStringList() << myQString); // possibility 1
myFunction(QStringList { myQString }); // possibility 2
Which possibility is more performant?
| Here is the benchmark:
#define ct_Benchmark(EXPR, repeat){\
int repeated = repeat;\
qint64 initialTime = QDateTime::currentMSecsSinceEpoch();\
qint64 totalTime = initialTime;\
EXPR;\
initialTime = QDateTime::currentMSecsSinceEpoch() - initialTime;\
for ( int ___i_ = 0; ___i_ < repeated; ___i_++) {\
EXPR;\
}\
totalTime = QDateTime::currentMSecsSinceEpoch() - totalTime;\
qreal averageTime = qreal( totalTime / repeated );\
const QString expression(#EXPR);\
const QString iterations(" Cycles: " + QString::number( repeated ) );\
const QString initial ("Initial: " + QString::number( initialTime ) );\
const QString total (" Total: " + QString::number( totalTime ) );\
const QString average ("Average: " + QString::number( averageTime, 'g', 24 ) );\
ct_Info(expression, iterations, initial, total, average);\
}
QString sneed("'s feed & seed. Formerly chucks.");
ct_Benchmark( QStringList{ sneed }, 1000000 );
ct_Benchmark( QStringList( QStringList() << sneed ), 1000000 );
Debug
Info /home/anon/Programming/QtConsoleDesigner/QtSandbox/src/sandbox.cpp:57
int main(int, char**)
QString expression
"QStringList( QStringList() << sneed )"
QString iterations
" Cycles: 10000000"
QString initial
"Initial: 0"
QString total
" Total: 3461"
QString average
"Average: 0"
Info /home/anon/Programming/QtConsoleDesigner/QtSandbox/src/sandbox.cpp:56
int main(int, char**)
QString expression
"QStringList{ sneed }"
QString iterations
" Cycles: 10000000"
QString initial
"Initial: 0"
QString total
" Total: 2094"
QString average
"Average: 0"
Release:
Info /home/anon/Programming/QtConsoleDesigner/QtSandbox/src/sandbox.cpp:57
int main(int, char**)
QString expression
"QStringList( QStringList() << sneed )"
QString iterations
" Cycles: 10000000"
QString initial
"Initial: 0"
QString total
" Total: 545"
QString average
"Average: 0"
Info /home/anon/Programming/QtConsoleDesigner/QtSandbox/src/sandbox.cpp:56
int main(int, char**)
QString expression
"QStringList{ sneed }"
QString iterations
" Cycles: 10000000"
QString initial
"Initial: 0"
QString total
" Total: 379"
QString average
"Average: 0"
Compiled using GCC.
Possibility 1 QStringList{ sneed } is about a third faster.
|
73,067,975 | 73,068,140 | What are these C++ Macros doing? | I'm new to C++ and trying to understand what these two macros are doing in this FileMaker Plugin Example.
#define FMX_PROC(retType) retType __stdcall
#define FMX_PROCPTR(retType, name) typedef retType (__stdcall *name)
So far I understand that they are both macros, and that the FMX_PROCPTR is a pointer to a function that takes those two arguments, and that __stdcall is some sort of calling convention (decided to not dig to much into what that means).
What I don't understand are the ends of each lines, the parts that come after FMX_PROC(retType) and FMX_PROCPT(retType, name).
It's possible that it is the spacing that is confusing me, but is retType __stdcall the return type for FMX_PROC(retType) ? Or is it giving the argument a type?
Somewhere else in the code FMX_PROC(retType) is used like this
static FMX_PROC(fmx::errcode) Do_FMmp_ConvertToBase( short /* funcId */, const fmx::ExprEnv& /* environment */, const fmx::DataVect& dataVect, fmx::Data& results )
| These macros are just to provide the calling-convention __stdcall into the function being defined, or a function pointer alias.
__stdcall is a non-standard compiler-intrinsic that ensures that functions documented with this attribute will be called with the stdcall calling-convention. This applies to the function itself.
So the macros respectively:
FMX_PROC expands into retType __stdcall, which provides __stdcall to the function. E.g.
FMX_PROC(fmx::errcode) Do_FMmp_ConvertToBase(...)
expands into:
fmx::errcode __stdcall Do_FMmp_ConvertToBase(...)
FMX_PROCPTR expands into a typedef of a function pointer, that is also documented with __stdcall. This is necessary because function pointers don't normally carry calling conventions -- so the compiler doesn't implicitly know when a function expects a different calling convention. To bind a function marked __stdcall to a function pointer, the function pointer itself must carry this information (which is why this alias is needed).
This expands into part of the function typedef:
FMX_PROCPTR(fmx::errcode,Do_FMmp_ConvertToBase)(...);
will expand into
typedef fmx::errcode(__stdcall *Do_FMmp_ConvertToBase)(...);
|
73,068,316 | 73,106,142 | How to make SCons export compile commands including flags pointing to a conda virtual environment? | I'm working on a C++ project that is built with SCons. I installed SCons using my system's package manager. The project has some dependencies that I installed into a virtual environment using conda. I followed the SCons documentation to export a compile_commands.json.
When I activate the project's conda environment, then run scons, everything compiles fine and a compile_commands.json is created. However, the exported compile commands are missing -I or -isystem flags that point to the include/ directory of the conda environment.
My editor (vim/Ycm) relies on clangd for linting and semantic completion, clangd relies on the exported compile commands and is not aware of the conda virtual environment. How can I make SCons export the required flags so that clangd can find the dependencies headers?
(For comparison, a different project that is set up the exact same way but using CMake exports compile commands with -isystem flags to the conda environment.)
| I got SCons to export the correct compile commands by adding the line
env.Append(CPPPATH= ['/path/to/my/conda/env/include'])
to the SConstruct file. I assume the reason for the compilation working even without this line is that the compiler is installed in the same conda environment.
|
73,068,731 | 73,156,555 | Xerces 3.2 XMLString::transcode not working on special characters | I have this xml file :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cmh>
<value atr="éè€ç"></value>
</cmh>
And this simple C++ program using Xerces 3.2.3:
...
//const XMLCh* xmlch_OptionA = currentElement->getAttribute(XMLString::transcode("atr")); --> this one always works
char* a = "éèç€";
//char* a = XMLString::transcode(xmlch_OptionA); --> this one does not work with these characters
cout << sizeof(char) << " " << a << std::endl;
cout << std::hex << (unsigned int)(a[0] &0xFF) << " " << (unsigned int)(a[1] &0xFF) << " " << (unsigned int)(a[2] &0xFF) << " " << (unsigned int)(a[3] &0xFF) << std::endl;
...
Output:
1 éèç€
c3 a9 c3 a8
This program works just fine but when I try to retrieve the char* from the XML file with XMLString:transcode (see the commented lines), I get nothing and I can't figure out why. I built this Xerces with Iconv as its transcoder, isn't it supposed to correctly handle these situations? Or maybe is there a way to achieve the same result without using transcode()?
Wrong output:
1
0 0 0 0
NB: Of course, it works if I replace the "éèç€" by something like "abcd".
| The problem was coming from the Docker image I was using (gcc:10.2).
The locale for en_US.UTF-8 was not installed on it.
So, I installed it and wrote at the beginning of my program:
setlocale(LC_ALL, "en_US.UTF-8");
XMLString::transcode works just fine now.
|
73,069,395 | 73,069,421 | How can I assign a const unsigned char value to a variable inside a condition in c++? | I am using C++ for programming a microcontroller, and I have this situation.
I have several const unsigned char in a .h file. Ex:
const unsigned char epd_bitmap_icon1 [] = {...
const unsigned char epd_bitmap_icon2 [] = {...
I have a function that takes one of this variables:
void drawBitmap(int16_t x, int16_t y, uint8_t *bitmap, int16_t w, int16_t h, uint16_t color);
In this case, I need to conditionally pass a different bitmap based on a certain value.
In python would be something like this:
if value > 80:
icon = epd_bitmap_icon1
elif value > 30:
icon = epd_bitmap_icon2
else:
icon = edp_bitmap_icon3
and later pass the icon value to drawBitmap as the third argument.
I don't know how to do it in C++, I have tried this:
if (batteryChargePercent > 80) {
unsigned char* icon = epd_bitmap_icon1;
}
else if (batteryChargePercent > 30) {
unsigned char* icon = epd_bitmap_icon2;
} else {
unsigned char* icon = epd_bitmap_icon3;
}
But I get this error:
error: invalid conversion from 'const unsigned char*' to 'unsigned char*' [-fpermissive]
| Declare the variable once outside the if, and assign it in the if.
const unsigned char *icon;
if (batteryChargePercent > 80) {
icon = epd_bitmap_icon1;
} else if (batteryChargePercent > 30) {
icon = epd_bitmap_icon2;
} else {
icon = epd_bitmap_icon3;
}
You need to use const in the pointer declaration to solve the error message.
|
73,069,843 | 73,078,685 | Query information about which data members function accesses | Assume the following example code
struct Bar {
int x, y, z;
};
int foo(const Bar& bar) {
return bar.x + bar.z;
}
Is there a way to automatically tell, that foo accesses x and z from bar, but not y? Maybe the compiler (any of gcc, clang, or msvc) can output something like that?
| One tool that can do this sort of thing is clang-query, which is
included in the
Clang+LLVM distribution. clang-query searches the program's Abstract Syntax Tree (AST) for code that matches the given pattern(s).
For example, here is a shell script that invokes clang-query to find member
accesses:
#!/bin/sh
# Run clang-query to find referenced members.
# Where I have Clang+LLVM installed.
CLANG_LLVM_DIR=$HOME/opt/clang+llvm-14.0.0-x86_64-linux-gnu-ubuntu-18.04
# This query reports member reference expressions (like "obj.field").
# It binds the name "field" to the matched field, and "func" to the
# function definition containing the reference.
query='m
memberExpr(
member(fieldDecl().bind("field")),
hasAncestor(functionDecl().bind("func")))'
# Run clang-query.
"$CLANG_LLVM_DIR"/bin/clang-query -c="$query" "$@"
# EOF
The core of query is memberExpr, a matcher that reports any
expression that is an access of a member. The rest is binding names to
relevant elements so they will be printed, as well as the member
expression itself.
When run on the input in the question, it prints:
$ ./cmd.sh test.cpp --
Match #1:
path_to_source/test.cpp:2:5: note: "field" binds here
int x, y, z;
^~~~~
path_to_source/test.cpp:5:1: note: "func" binds here
int foo(const Bar& bar) {
^~~~~~~~~~~~~~~~~~~~~~~~~
path_to_source/test.cpp:6:12: note: "root" binds here
return bar.x + bar.z;
^~~~~
Match #2:
path_to_source/test.cpp:2:5: note: "field" binds here
int x, y, z;
^~~~~~~~~~~
path_to_source/test.cpp:5:1: note: "func" binds here
int foo(const Bar& bar) {
^~~~~~~~~~~~~~~~~~~~~~~~~
path_to_source/test.cpp:6:20: note: "root" binds here
return bar.x + bar.z;
^~~~~
2 matches.
This is reporting both of the accesses.
If you want to do more than just print the accesses, you will probably
need to write something like a clang-tidy check. Such a check uses AST
matchers like clang-query, but you can also write arbitrary
C++ code to process the matches.
References:
Clang AST Matcher Reference
Clang AST: MemberExpr,
which is one of many Clang AST nodes. Although it is not necessary to look at the AST documentation to write matchers, I find it helpful since the matcher names are based on names in the main AST docs.
Writing custom clang-tidy checks
Stephen Kelly blog: Exploring Clang Tooling Part 2: Examining the Clang AST with clang-query: https://devblogs.microsoft.com/cppblog/exploring-clang-tooling-part-2-examining-the-clang-ast-with-clang-query
Firefox blog:
Using clang-query
|
73,069,864 | 73,071,419 | how to output float to tiff using CImg? | I'm trying to have float values in a .tiff file. The values in display are fine, but once on disk, it is unsigned short.
#include<X11/Xlib.h>
#include "CImg.h"
#define cimg_use_tif
using namespace cimg_library;
int main()
{
CImg<float> imgFloat(640, 400);
for(int i=0; i<640; i++)
for(int j=0; j<400; j++)
imgFloat(i,j) = float(i*640+j)/10000;
imgFloat.save_tiff("V_float.tiff"); // cant get anything but unsigned short in the actual output
imgFloat.display();
return(0);
}
| You need:
#define cimg_use_tif
before (i.e. above)
#include "CImg.h"
Or actually, preferably define it on the compilation command-line:
g++ -D cimg_use_tif ...
|
73,069,990 | 73,070,662 | How to update (closure) so that it keeps updating | So in this code, what I have to do is, I want to set my ROIto 8% initially, and changes so on
It has to be done with closure concept. I got confused here and tried very much before asking for the help.
if (Math.random() > 0.5) {
const x = 1;
} else {
const x = 2;
}
console.log(x);
Believe me, I tried so much before asking for the help. Please help me to correct this.
| If I understand correctly you want to be able to update the rate of interest while externally to the calculating function. Instead of using global variable we use closure. However, since there are 2 functions involved I return them in an object.
const createLoanCalculator = (rateOfInterest, principle, term) => {
var installment = 1; // ?
var _rateOfInterest = rateOfInterest;
const updatedRateOfInterest = (x) => {
_rateOfInterest = x;
}
const simpleInterest = (principle, term) => {
simpleInterestValue = _rateOfInterest * principle * installment / 100;
return simpleInterestValue;
}
return {
updatedRateOfInterest,
simpleInterest
};
}
const obj_calculator = createLoanCalculator(8, 4000, 6);
var simpleInterest = obj_calculator.simpleInterest
var updatedRateOfInterest = obj_calculator.updatedRateOfInterest
console.log(simpleInterest(200, 30));
updatedRateOfInterest(12)
console.log(simpleInterest(200, 30));
|
73,070,072 | 73,071,309 | Move dynamic memory to new array, releasing the old memory and not call destructor | I am implementing a storage class a bit different than std::vector and I ran into a problem when expanding the storage.
Current code to double the size:
//T is template class
//_elements is a T* to current array
T* old = _elements;
_elements = new T[size * 2];
memcpy(_elements, old, size * sizeof(T));
delete[] old;
size *= 2;
The problem is that delete[] calls the destructor.
Is there a way to free the old memory without calling destructor?
| You need to separate memory (de)allocation and constructor/destructor invocation.
memcpy won't work for non-trivial types; you should be using std::uninitialized_move instead.
The following code is an example of a container allowing to append only. The relevant member function for resizing the storage is emplace_back:
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <new>
#include <string>
#include <memory>
#include <utility>
#include <new>
template<class T>
class Container
{
T* m_data { nullptr };
size_t m_size{ 0 };
size_t m_capacity{ 0 };
/**
* Allocate uninitialized storage for \p n elements
* \exception ::std::bad_alloc if the memory could not be allocated
*/
static T* Alloc(size_t n)
{
if (n == 0)
{
return nullptr;
}
T* result = static_cast<T*>(
#ifdef _MSC_VER
_aligned_malloc(sizeof(T) * n, alignof(T))
#else
std::aligned_alloc(alignof(T), sizeof(T) * n)
#endif
);
if (result == nullptr)
{
throw std::bad_alloc();
}
return result;
}
/**
* Destruct \p n elements stored starting at \p data and free the memory.
*/
static void Destroy(T* data, size_t n) noexcept
{
std::destroy(data, data + n);
#ifdef _MSC_VER
_aligned_free
#else
std::free
#endif
(data);
}
public:
Container() = default;
// prevent copy & move for now
Container(Container&&) = delete;
Container& operator=(Container&&) = delete;
~Container()
{
Destroy(m_data, m_size);
}
template<class...Args>
T& emplace_back(Args&&... args)
{
if (m_size >= m_capacity)
{
// move old data to new storage
auto newCapacity = std::max<size_t>(16, m_capacity * 2);
auto newMemory = Alloc(newCapacity);
std::uninitialized_move(m_data, m_data + m_size, newMemory);
Destroy(m_data, m_size);
m_data = newMemory;
m_capacity = newCapacity;
}
// append element
auto& result = *std::construct_at<T>(m_data + m_size, std::forward<Args>(args)...);
++m_size;
return result;
}
T const* begin() const noexcept
{
return m_data;
}
T const* end() const noexcept
{
return m_data + m_size;
}
};
int main() {
Container<std::string> container;
for (int i = 0; i != 100; ++i)
{
container.emplace_back(std::to_string(i));
}
for (auto& element : container)
{
std::cout << element << '\n';
}
}
|
73,070,364 | 73,113,455 | How to execute commands in FarManager running in Windows console | I have a client server application. Using the CreateProcess() function, a new process is created on the server, which is actually like a remote console. The client sends a command, it is executed in the server console and returns the result back to the server. To communicate with the console, I use WriteFile() and ReadFile(). This part works great.
But I also need to be able to run FarManager in the server console and manage it.
I am able to run FarManager on the server using an environment variable, or by directly specifying it when creating a process. But after running the program, I can't issue any commands (for example, pressing the down arrow). It looks like the current implementation of pipes is not suitable for this task.
Can anyone suggest what might be useful for this?
CreateProcess function:
I am not attaching all the related structures, because the problem does not seem to be in the process itself
TCHAR szCmdline[] = TEXT("C:\\Windows\\System32\\cmd.exe");
TCHAR prog[] = TEXT("D:\\Program Files\\Far Manager x86\\Far.exe");
// Create the child process.
bSuccess = CreateProcess(
prog, // far
szCmdline, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
CREATE_NEW_CONSOLE, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&si, // STARTUPINFO pointer
&pi); // receives PROCESS_INFORMATION
WriteToPipe function:
bool WriteToPipe(char* com)
{
OVERLAPPED osWrite = { 0 };
DWORD dwWritten;
DWORD dwRes;
BOOL fRes;
// Create this write operation's OVERLAPPED structure's hEvent.
osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osWrite.hEvent == NULL) {
// error creating overlapped event handle
throw std::exception("Error creating overlapped event");
}
// Issue write.
if (!WriteFile(console_stdIn_wr, com, strlen(com), &dwWritten, &osWrite)) {
if (GetLastError() != ERROR_IO_PENDING) {
// WriteFile failed, but isn't delayed. Report error and abort.
std::cout << " WriteFile failed, but isn't delayed" << std::endl;
fRes = FALSE;
}
else {
// Write is pending.
dwRes = WaitForSingleObject(osWrite.hEvent, INFINITE);
switch (dwRes)
{
// OVERLAPPED structure's event has been signaled.
case WAIT_OBJECT_0:
if (!GetOverlappedResult(console_stdIn_wr, &osWrite, &dwWritten, FALSE))
fRes = FALSE;
else
// Write operation completed successfully.
fRes = TRUE;
break;
default:
// An error has occurred in WaitForSingleObject.
// This usually indicates a problem with the
// OVERLAPPED structure's event handle.
fRes = FALSE;
break;
}
}
}
else {
// WriteFile completed immediately.
fRes = TRUE;
}
CloseHandle(osWrite.hEvent);
return fRes;
}
I don't understand how I can issue commands to the open FarManager? Which function is worth looking at, and is the current implementation of pipes suitable for this?
| I am attaching my solution based on the advice of @YurkoFlisk. Maybe it can be useful for someone
//Execute command in FarManager
//nVirtKey - code of virtual key to run in far
void RunFar(int nVirtKey){
std::cout << "Key code "<< nVirtKey << std::endl;
//Create structure with buttons and their state
INPUT inputs[2] = {};
ZeroMemory(inputs, sizeof(inputs));
//Set key, that must be "pressed"
inputs[0].type = INPUT_KEYBOARD;
inputs[0].ki.wVk = nVirtKey;
//Set state of key
inputs[1].type = INPUT_KEYBOARD;
inputs[1].ki.wVk = nVirtKey;
inputs[1].ki.dwFlags = KEYEVENTF_KEYUP;
//Set position of window with FarManger to the foreground (by the handle of window)
SetForegroundWindow(hwnd);
//Send key structure to window
UINT uSent = SendInput(ARRAYSIZE(inputs), inputs, sizeof(INPUT));
}
|
73,070,739 | 73,070,919 | Vector of pointers saving a pointer to a vector of ints | just wondering if you can point to a pointer that points to a vector of ints. And save the pointer that points to a vector of ints. Here's the code I'm trying to pull off.
Probably dosen't make sense but I'm trying to make it work for a while now, bare with me. But I want to pull this way somehow.
int n, q;
cin >> n >> q;
vector <int*> ar;
for (int i=0;i<n;i++){
int k;
cin >> k;
vector< int > *vec;
for(int j = 0;j<k;j++){
(*(vec+j)).push_back(cin.get());
}
ar.push_back(&(vec));
}
Thanks for the possible help. Haven't seen this asked in here, just things a bit different than this.
| I think this is what you're trying to achieve here:
int n, q;
cin >> n >> q;
vector<vector<int>*> ar;
for (int i=0;i<n;i++){
int k;
cin >> k;
vector<int> *vec = new vector<int>;
for(int j = 0;j<k;j++){
vec->push_back(cin.get());
}
ar.push_back(vec);
}
// do not forget to delete the inner vectors before removing them from ar!
What you end up with is a vector ar that contains pointers to other vectors which in turn contain ints.
I don't see though why you would want to store pointers here at all, a nested vector works fine:
int n, q;
cin >> n >> q;
vector<vector<int>> ar;
for (int i=0;i<n;i++){
int k;
cin >> k;
vector<int> vec;
for(int j = 0;j<k;j++){
vec.push_back(cin.get());
}
ar.push_back(vec);
}
|
73,070,998 | 73,071,233 | Invoking a member function with variadic template parameters that are not part of the function's arguments | Most of the questions I have found revolve around non-member functions where the variadic template parameters are also found in the function's arguments.
In my case, I am in a situation where I would like to filter the types coming into one of the variadic member functions and pass the filtered types to another variadic member function:
#include <tuple>
#include <type_traits>
template<typename...Ts>
using tuple_cat_t = decltype(std::tuple_cat(std::declval<Ts>()...));
// how the filtering of the types happen is not relevant
template<typename T, typename...Ts>
using remove_t = tuple_cat_t<
typename std::is_empty_v<T>,
std::tuple<>,
std::tuple<Ts>
>::type...
>;
struct Foo
{
template <typename... T_Tags>
void Bar(float arg)
{
// I would like to call DoBar() with a filtered set of T_Tags
// where type filtering is done with something similar to what is outlined
// here: https://stackoverflow.com/a/23863962/368599
using filtered_args = std::remove_t<T_Tags...>;
// not sure of the syntax here or if this is even possible
std::invoke(&Foo::DoBar<???filtered_args???>, std::tuple_cat(std::make_tuple(this), std::make_tuple(arg)));
}
template <typename... T_FilteredTags>
void DoBar(float arg)
{
// Do something with T_FilteredTags types
}
};
| You can use template lambda to expand the filtered types and specify them to DoBar explicitly
struct Foo
{
template <typename First_Tag, typename... T_Tags>
void Bar(float arg)
{
using filtered_args = remove_t<First_Tag, T_Tags...>;
[&]<typename... T_FilteredTags>(std::tuple<T_FilteredTags...>*) {
std::invoke(&Foo::DoBar<T_FilteredTags...>, this, arg);
} (static_cast<filtered_args*>(nullptr));
}
template<typename... T_FilteredTags>
void DoBar(float arg)
{
// Do something with T_FilteredTags types
}
};
Noted that there is no need to use tuple to concatenate this and arg, just pass them to std::invoke directly.
Demo
|
73,071,015 | 73,076,467 | Change default class item template provided by AddClass Wizard in vs2017 | I want to create a class template that would account for the precompiled header if present (which happens with the default add class wizard), but I'd like to expand the barebone template provided by the wizard with a constructor, (possibly virtual) destructor and a bunch of private and public sections. I have read the microsoft pages talking about item templates, but I cannot seem to find the functionality that would allow me to account for the precompiled header.
Is there a way (even a hacky one) of modifying the add class wizard without having to create a vs extension from scrap?
Something similar seems to be possible with C# templates as can be seen from various posts advising to modify Class.cs in C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class, unfortunately, I cannot find the C++ equivalent.
| What you want to achieve is somewhat difficult:
override default c++ class template in visual studio 2010
modify item template may be easier:
1.Add class through class wizard and code
#pragma once
class Myclass
{
public:
Myclass();
~Myclass();
protected:
int test();
private :
};
Tool bar: Project-> Export Template->Item template
Then you can add custom item(may need to restart Visual Studio)
E.g.
#pragma once
class hello
{
public:
hello();
~hello();
protected:
int test();
private :
};
|
73,071,103 | 73,071,548 | class template specialization based on literal type using enable_if | I am trying to create a Vector class, templated on a type T and number of elements NUM_VALUES . I want the class to use a std::vector to store its elements when NUM_VALUES > 16384 and a std::array<T, NUM_VALUES> to stores its elements when NUM_VALUES <= 16384. At first I tried doing the following:
vector.h:
#include <array>
#include <vector>
#include <cstddef>
template <typename T, std::size_t NUM_VALUES, typename Elements = std::vector<T>>
class Vector
{
public:
constexpr const char* hello()
{
return "hello";
}
};
template <typename T, std::size_t NUM_VALUES>
class Vector<T, NUM_VALUES, typename std::enable_if<NUM_VALUES <= 16384, std::array<T, NUM_VALUES>>::type>
{
public:
constexpr const char* hello()
{
return "Hello";
}
};
main.cpp
#include "vector.h"
#include <iostream>
int main()
{
Vector<int, 10> vec1;
Vector<int, 1000000> vec2;
std::cout << vec1.hello() << ", " << vec2.hello();
return 0;
}
However this always selects the primary template, so I get "hello", "hello" instead of "hello", "Hello". I tried fixing this by changing vector.h to:
#include <array>
#include <vector>
#include <cstddef>
template <typename T, std::size_t NUM_VALUES, typename Elements = typename std::enable_if<16384 < NUM_VALUES, std::vector<T>>::type>
class Vector
{
public:
constexpr const char* hello()
{
return "hello";
}
};
template <typename T, std::size_t NUM_VALUES>
class Vector<T, NUM_VALUES, typename std::enable_if<NUM_VALUES <= 16384, std::array<T, NUM_VALUES>>::type>
{
public:
constexpr const char* hello()
{
return "Hello";
}
};
but got the error:
\MyVector\main.cpp(7,16): error C2146: syntax error: missing '>' before identifier 'type'
\MyVector\MyVector\main.cpp(7,2): error C2976: 'Vector': too few template arguments
\MyVector\MyVector\vector.h(9): message : see declaration of 'Vector'
\MyVector\MyVector\main.cpp(7,18): error C2146: syntax error: missing '>' before identifier 'type'
\MyVector\MyVector\main.cpp(7): error C2641: cannot deduce template arguments for 'Vector'
\MyVector\MyVector\main.cpp(7): error C2783: 'Vector<T,NUM_VALUES,Elements> Vector(void)': could not deduce template argument for 'T'
\MyVector\MyVector\vector.h(9): message : see declaration of 'Vector'
\MyVector\MyVector\main.cpp(7): error C2783: 'Vector<T,NUM_VALUES,Elements> Vector(void)': could not deduce template argument for 'NUM_VALUES'
\MyVector\MyVector\vector.h(9): message : see declaration of 'Vector'
\MyVector\MyVector\main.cpp(7,22): error C2780: 'Vector<T,NUM_VALUES,Elements> Vector(Vector<T,NUM_VALUES,Elements>)': expects 1 arguments - 0 provided
\MyVector\MyVector\vector.h(9): message : see declaration of 'Vector
I am using visual studio 2022 to compile the code.
| Type SFINAE is not part of the C++ standard, but you could easily accomplish the desired results in a different manner.
Define seperate templates for both alternatives. Then define an alias template Vector that uses std::conditional_t to detemine the type to use:
constexpr std::size_t SmallVectorMaxSize = 16384;
template <typename T, std::size_t NUM_VALUES>
class BigVector
{
public:
static_assert(NUM_VALUES > SmallVectorMaxSize);
using Elements = std::vector<T>;
constexpr const char* hello()
{
return "hello";
}
};
template <typename T, std::size_t NUM_VALUES>
class SmallVector
{
public:
static_assert(NUM_VALUES <= SmallVectorMaxSize);
using Elements = std::array<T, NUM_VALUES>;
constexpr const char* hello()
{
return "Hello";
}
};
template<class T, size_t N>
using Vector = std::conditional_t<N <= SmallVectorMaxSize, SmallVector<T, N>, BigVector<T, N>>;
int main()
{
Vector<int, 10> vec1;
Vector<int, 1000000> vec2;
std::cout << vec1.hello() << ", " << vec2.hello();
return 0;
}
|
73,071,556 | 73,074,329 | Why a std::get_time() simple example fails parsing on WSL Ubuntu 20.04? | I am trying to run a very simple example of the std::get_time() function but the parse is failing.
#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>
int main()
{
std::tm t = {};
std::istringstream ss("04-02-2022 3:04:32");
ss >> std::get_time(&t, "%m-%d-%Y %H:%M:%S");
if (ss.fail()) {
std::cout << "Parse failed\n";
if ((ss.rdstate() & std::istringstream::failbit) != 0)
std::cerr << "Error failbit\n";
if ((ss.rdstate() & std::istringstream::goodbit) != 0)
std::cerr << "Error goodbit\n";
if ((ss.rdstate() & std::istringstream::eofbit) != 0)
std::cerr << "Error eofbit\n";
if ((ss.rdstate() & std::istringstream::badbit) != 0)
std::cerr << "Error badbit\n";
}
else {
std::cout << std::put_time(&t, "%c") << '\n';
}
}
I am using Ubuntu 20.04 in Windows via WSL, which has g++ 9.4 installed, and I am compiling with the terminal command:
g++ -std=c++17 date.cpp -o date
The error is std::istringstream::failbit
Any Ideas what is going on?
| I was able to reproduce the failure in gcc 9.4. It works if you change 3 to 03 in the hour field.
Even though %H is not supposed to require a leading zero, this appears to be a gcc bug where it does. See Bug 78714. Despite being about %b, this comment in that ticket goes into detail about how it also affects %H and other placeholders, too.
The code works fine in gcc 12.1.
Demo
|
73,071,644 | 73,071,651 | how to use batch in c++ | I have a batch program that I would like to add to one of my c++ programs. The batch program tests if a file exists and exits the script if it doesn't. I do not want to add any more libraries to my code. The problem that I have is that I am not sure how I am able to use batch in c++. I am able to figure everything else out on my own I just need to know this one thing.
| You can use the system(" ") command to use batch.
|
73,071,707 | 73,071,791 | C++ template argument-dependent lookup | namespace Test {
template<typename T>
void foo(T a) {
g(a);
}
struct L {
int s;
};
void bar(L a) {
g(a);
}
}
int main() {
foo(Test::L{1});
g(Test::L{5});
}
namespace Test {
void g(L a) {};
}
why in foo, g can be found, but in bar and main, g cannot be found.
Tested with gcc 11.2.0 under C++11.Here is the error message.
/tmp/tmp.l8jCE9nUHA/test1.cpp: In function ‘void Test::bar(Test::L)’:
/tmp/tmp.l8jCE9nUHA/test1.cpp:33:9: error: ‘g’ was not declared in this scope
33 | g(a);
| ^
/tmp/tmp.l8jCE9nUHA/test1.cpp: In function ‘int main()’:
/tmp/tmp.l8jCE9nUHA/test1.cpp:39:5: error: ‘g’ was not declared in this scope
39 | g(Test::L{5});
| ^
| Even without the call to g in main and bar, the program is still ill-formed, but with no diagnostic required.
The argument-dependent lookup in a template specialization is done from the point of instantiation of the specialization, not from the point of the definition of the template.
The specialization Test::foo<Test::L> is implicitly instantiated due to the call foo(Test::L{1}); in main. As a consequence it has two points of instantiation: One directly after the definition of main and one at the end of the translation unit. (This is always the case for function template specializations.)
At the first point of instantiation Test::g has not been declared yet and argument-dependent lookup would fail. At the second point of instantiation it would succeed since Test::g has been declared there and can be found through argument-dependent lookup via the Test::L argument.
If two points of instantiation give different meaning to the program, the program is IFNDR (ill-formed, no diagnostic required), meaning that it is still an invalid program, but the compiler doesn't have to tell you about it, analogues to ODR violations.
To avoid this you should declare all functions g that Test::foo<Test::L> would potentially use before the namespace scope declaration which is first making a call to Test::foo<Test::L> (or making some other ODR-use of it). Here this means you should declare g before main's definition.
The calls g(Test::L{5}); in main and g(a); in bar simply make the program ill-formed, with a diagnostic required, because neither appears in the definition of a templated entity, so argument-dependent lookup is done directly from where these calls appear and both of these are before g has been declared, so that no g can be found. To make them work g must be declared before these calls.
|
73,073,150 | 73,073,174 | variables declaration in anonymous namespace and definition in other place | Can someone explain why I can't define variable that was declared in anonymous namespace as global variable in another place?
#include <iostream>
namespace {
extern int number;
}
int number = 123;
void g() {
std::cout << number;
}
Compiler says that "Reference to 'number' is ambiguous" but I can't understand why it recognises declaration and definition as different things? Thank you in advance.
| For the unqualified name-lookup the compiler considers also nested unnamed namespaces in the global namespace,
You declared two different objects with the same name in the global namespace and in the nested unnamed namespace.
The using directive for unnamed namespace is implicitly inserted in the enclosing namespace.
Consider the following demonstration program
#include <iostream>
namespace N
{
extern int number;
}
using namespace N;
int number = 123;
int main()
{
std::cout << number << '\n';
}
The compiler will issue an error due to the ambiguity for the unqualified reference to the name number in this statement
std::cout << number << '\n';
The similar situation takes place with an unnamed namespace because the using directive is implicitly inserted in the enclosing namespace.
From the C++ 20 Standard (9.8.2 Namespace definition)
7 Members of an inline namespace can be used in most respects as
though they were members of the enclosing namespace. Specifically, the
inline namespace and its enclosing namespace are both added to the set
of associated namespaces used in argument-dependent lookup (6.5.3)
whenever one of them is, and a using directive (9.8.4) that names
the inline namespace is implicitly inserted into the enclosing
namespace as for an unnamed namespace (9.8.2.2).
|
73,073,694 | 73,073,750 | CMake generating .sln files and other VS files | I am new to learning CMake, and as I am going through tutorials, I am running the command Cmake -S -B, but instead of creating a makefile, it is making lots of vcxproj files and a Project.sln.
From what i understnand, cmake can make VS files, but I want it to just make Makefiles. How do I get it back?
| Set "Unix Makefiles" to variable CMAKE_GENERATOR
|
73,073,696 | 73,073,725 | Mimicking C calloc array behavior in C++ | There is some code that exists in C which uses calloc() to create what effectively is a vector. It looks like this:
uint64_t *reverseOrder = (uint64_t *)calloc((size + 1), sizeof(uint64_t));
I want to mimic this behavior with C++ syntax and vectors so that it works the same de-facto. Can I use the following syntax?
std::vector<uint64_t> reverseOrder(size + 1, 0);
I know that calloc() actually goes through the memory and sets them to 0, so I'm wondering if this is the case.
| You can just write
#include <vector>
#include <cstdint>
//...
std::vector<uint64_t> reverseOrder( size + 1 );
and all elements of the vector will be zero-initialized.
|
73,074,052 | 73,084,414 | Returning const reference to temporary | Why does the function foo gives the warning "returning reference to temporary"
const bool& foo()
{
return true;
}
if declaring bar like this is fine and doesn't generate any kind of warning
const bool& bar = true;
PS: i'm using GCC
| songyuanyao answered with what the standard says about it. But that doesn't really explain why they decided c++ should behave this way.
It might be easier to think about the code if you think about what the compiler makes of it:
const bool& bar = true;
The lifetime of the temporary is extended to the lifetime of bar so this code is equivalent to:
const bool temp = true;
const bool& bar = temp;
But lets apply the same to the function return:
const bool& foo()
{
return true;
}
becomes
const bool& foo()
{
const boot temp = true
return temp;
}
Does this make it clearer that you are now returning a reference to an object that gets destroyed? The lifetime of temp can't be extended past the end of the function because 1) the storage location is in the stack frame of fooand that goes away, 2) the caller might have no idea the function returns something with extended lifetime it would have to destroy later, it might only see the function declaration const bool& foo().
So if the compiler could extend the lifetime past the end of the function then it would leak memory.
|
73,074,150 | 73,087,141 | Calling C++/CLI DLL from IronPython leading to an "not a valid Win32 application. (Exception from HRESULT: 0x800700C1)" error | I've been trying to implement this tutorial:
https://www.red-gate.com/simple-talk/development/dotnet-development/creating-ccli-wrapper/
and even though it works. When I try to call the Wrapper.dll from IronPython I get an error.
I cannot even load the DLL.
This is the IronPython code:
import clr
clr.AddReferenceToFileAndPath("Wrapper.dll")
clr.AddReference("mscorlib")
import CLI
import System
if __name__ == "__main__":
e = CLI.Entity("the guy", 54, -123)
e.Move(-54, 123)
System.Console.WriteLine(e.XPosition + " " + e.YPosition)
Could anyone please explain what the issue is and hint me a potential solution?
| The answer to my question is:
re-build all projects in x64 just because IronPython used is x64 build.
|
73,074,164 | 73,074,247 | Using a C++ DLL in Flutter The type must be a subtype | dll` to my flutter project
In .dll I type function:
int testdll(int param) {
//...
}
on flutter I type this:
final DynamicLibrary nativePointerTestLib = DynamicLibrary.open("assets/SimpleDllFlutter.dll");
final Int Function(Int arr) testdllflutter =
nativePointerTestLib
.lookup<NativeFunction<Int Function(Int)>>("testdll")
.asFunction();
and I get error
The type 'Int Function(Int)' must be a subtype of 'Int Function(Int)' for 'asFunction'. (Documentation)
Int is defined in C:\flutter\bin\cache\pkg\sky_engine\lib\ffi\c_type.dart (c_type.dart:77).
Int is defined in C:\flutter\bin\cache\pkg\sky_engine\lib\ffi\c_type.dart (c_type.dart:77).
Try changing one or both of the type arguments.
Do you have any ideas?
| I try call wrond types, correct types:
final int Function(int arr) testdllflutter =
nativePointerTestLib
.lookup<NativeFunction<Int32 Function(Int32)>>("testdll")
.asFunction();
and it works
|
73,074,294 | 73,075,830 | Singleton creating in c++ | Why when we use singleton in c++ we create a method to construct static object of class but don't use static object?
I mean why we do this:
#include <iostream>
struct Singleton {
public:
static Singleton& instance() {
static Singleton s;
return s;
}
void getter() {
std::cout << "asd";
}
private:
Singleton() = default;
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
};
int main() {
Singleton& s = Singleton::instance();
}
but not this:
#include <iostream>
struct Singleton {
public:
static Singleton s;
void getter() {
std::cout << "asd";
}
private:
Singleton() = default;
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
};
int main() {
Singleton::s.getter();
}
I mean why does we need a method to construct static object if we can just create static object and work with it?
| The short answer is that people do what you are asking about because they want to avoid bugs resulting from global variables being initialized out of order. In particular, suppose that some other global variable made use of the singleton object in its initialization. You'd run the risk that the second object uses the first uninitialized, if the initialization happens in the wrong order. With the function-level static object, you are guaranteed that the object is initialized at the time you use it.
Note you'll need to define s in exactly one translation unit, even while it's declared in every unit (in the header file).
|
73,074,345 | 73,074,409 | private: static class member initialization with inclass setter called by method in different class returns error - unresolved symbols | The question is a duplicate in concept, but the error is articulated differently. Unresolved symbols should be understood as undefined reference. If you are new to C++, please take the time to read the errors generated by my code.
I am taking a course in C++ and OOP, and I need some help understanding what I am doing wrong and what I can do to correct it.
I have a code skeleton, where I cannot change class members by changing them from static to non-static. In my current hand-out, I need to create an object of the first class in a second class, and call a method in the first class. I cannot move class members from private to public or public to private, and I cannot change them from static to non-static.
My goal is to write methods in the second class that uses the setters and getters from the first class, using an object in the second class, and to call the methods in the second class in int main().
Here is a basic idea of what I have written in attempting what I described.
#include <iostream>
using namespace std;
class foo
{
private:
static string goo;
static long int doo;
public:
static void setGoo(string gooString)
{
goo = gooString;
}
static void setDoo(long int dooLongInt)
{
doo = dooLongInt;
}
static string getGoo()
{
return goo;
}
static long int getDoo()
{
return doo;
}
};
class moo
{
private:
foo fooObj;
public:
void setGoo(string gooString)
{
fooObj.setGoo(gooString);
}
void setDoo(long int dooLongInt)
{
fooObj.setDoo(dooLongInt);
}
string getGoo()
{
return fooObj.getGoo();
}
long int getDoo()
{
return fooObj.getDoo();
}
};
int main()
{
moo mainMoo;
string text = "Text";
mainMoo.setGoo(text);
mainMoo.setDoo(123);
cout << mainMoo.getGoo();
cout << mainMoo.getDoo();
return 0;
};
I get these errors when I compile it.
1>Source.obj : error LNK2001: unresolved external symbol "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > foo::goo" (?goo@foo@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A)
1>Source.obj : error LNK2001: unresolved external symbol "private: static long foo::doo" (?doo@foo@@0JA)
1>C:\Users\ipyra\OneDrive\Documents\edx hands-on projects\Static class private member initialization\x64\Debug\Static class private member initialization.exe : fatal error LNK1120: 2 unresolved externals
| Class static members need to initialize outside a class, that is the reason of link error.
class foo
{
private:
static string goo;
static long int doo;
public:
// .... other code
};
string foo::goo = "";
long int foo::doo = 0;
Use inline keyword in C++ 17, we can defined static member inside class.
http://en.cppreference.com/w/cpp/language/static
Another similar question
How to initialize private static members in C++?
|
73,074,670 | 73,074,825 | Does it make sense to use a reference in this case? | I wonder if it makes sense to use references when using literal constants.
Below i made a few examples:
bool funcWithoutReference(const std::string Text)
{
return Text == "Hello!";
}
bool funcWithReference(const std::string& Text)
{
return Text == "Hello!";
}
int main()
{
// Example 1: Average execution time: 13.652 sec
for (int i = 0; i < 10000000; i++) {
std::string text = "Hello";
funcWithoutReference(text);
}
// Example 2: Average execution time: 7.283 sec
for (int i = 0; i < 10000000; i++) {
funcWithoutReference("Hello");
}
// Example 3: Average execution time: 7.249 sec
for (int i = 0; i < 10000000; i++) {
std::string text = "Hello";
funcWithReference(text);
}
// Example 4: Average execution time: 7.292 sec
for (int i = 0; i < 10000000; i++) {
funcWithReference("Hello");
}
return 0;
}
Why is there such a difference between examples 1 and 2? I understand that using a literal constant in memory a "temporary" variable is created and passed as a parameter to the function. But why does example 2 get results almost like 3 and 4? Is a copy only made when we pass a variable as a parameter?
Time was measured as standard, using clock_t.
Thanks for your help.
| Examples 2, 3, and 4 are identical. In each, you create a single std::string per loop iteration. Example 1 does this too, but also copies it.
Let's break it down...
Example 1
Total string objects: 2
std::string text = "Hello";
funcWithoutReference(text);
Every time around the loop, you create a new string, initialized from the literal "Hello". You then pass it by value, so it is copied as a result of the function call.
Example 2
Total string objects: 1
funcWithoutReference("Hello");
Every time around the loop, you create a temporary string, initialized from the literal "Hello". This happens as a result of resolving the function call that will implicitly convert the literal to a std::string by way of one of its available constructors. This string is an rvalue, meaning a temporary result. It only exists for the duration of the function call.
Example 3
Total string objects: 1
std::string text = "Hello";
funcWithReference(text);
Every time around the loop, you create a new string, initialized from the literal "Hello". You then pass this by reference, so no additional copies are made.
Example 4
Total string objects: 1
funcWithReference("Hello");
Every time around the loop, you create a temporary string, initialized from the literal "Hello". This happens as a result of resolving the function call that requires a const std::string&. To achieve that, the literal is first implicitly converted to a std::string rvalue by way of one of its available constructors. That is then provided by reference.
Notes
It should be pointed out that your test might be a bit bogus. These loops have no actual side-effects, and could potentially be optimized away completely. And Example 1 could also be optimized to elide the copy because there is no other use or side-effect for the local string.
Improvement
To avoid the overhead of allocating a new std::string, you may choose to use std::string_view (since C++17). This is a light-weight string-like interface that works on both literals and std::string. It does not do any dynamic allocation.
The cost of copying a string_view is therefore very low so you can pass them by value or reference without incurring a significant difference in computational cost.
#include <string_view>
bool funcWithoutReference(std::string_view Text)
{
return Text == "Hello!";
}
bool funcWithReference(const std::string_view& Text)
{
return Text == "Hello!";
}
int main()
{
// No allocation per iteration
for (int i = 0; i < 10000000; i++) {
funcWithoutReference("Hello");
}
for (int i = 0; i < 10000000; i++) {
funcWithReference("Hello");
}
// Single allocation per iteration
for (int i = 0; i < 10000000; i++) {
funcWithoutReference(std::string{"Hello"});
}
// Single allocation per iteration
for (int i = 0; i < 10000000; i++) {
funcWithReference(std::string{"Hello"});
}
}
|
73,074,748 | 73,074,943 | Rearrange array non-negative numbers to the left and into ascending order C++ | I already arrange non-negative numbers to the left side of the array, now I want to put the sort function to rearrange numbers in ascending order into my program but it didn't work, I can't have them both, can you all help please? I'm totally new to this.
int tg;
for(int i = 0; i < n - 1; i++){
for(int j = i + 1; j < n; j++){
if(a[i] > a[j]){
tg = a[i];
a[i] = a[j];
a[j] = tg;
}
}
}
#include<bits/stdc++.h>
using namespace std;
void segregateElements(int arr[], int n)
{
int temp[n];
int j = 0; // index of temp
for (int i = 0; i < n ; i++)
if (arr[i] >= 0 )
temp[j++] = arr[i];
if (j == n || j == 0)
return;
for (int i = 0 ; i < n ; i++)
if (arr[i] < 0)
temp[j++] = arr[i];
memcpy(arr, temp, sizeof(temp));
}
int main()
{
int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
segregateElements(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
1 7 5 11 6 -1 -3 -2
Expected:
1 5 6 7 11 -1 -2 -3
| First,a part of your code is this
int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 };
but,the output you want is
1 2 3 6 11 -1 -5 -7
You maybe make some mistakes : there is no -7 in the arr
I think the code below will solve your problem
#include <cstring>
#include <iostream>
using namespace std;
void segregateElements(int arr[], int n)
{
int temp[n];
int j = 0; // index of temp
for (int i = 0; i < n ; i++)
if (arr[i] >= 0 )
temp[j++] = arr[i];
if (j == 0 || j == 1)
return;
for(int i = 0;i < j;i++){
for (int k = 0;k < j - 1;k++){
if (temp[k+1]<temp[k]){
int tg = temp[k+1];
temp[k+1] = temp[k];
temp[k] = tg;
}
}
}
for (int i = j;i < n;i++){
for (int k = j;k < n - 1;k++){
if (temp[k+1]<temp[k]){
int tg = temp[k+1];
temp[k+1] = temp[k];
temp[k] = tg;
}
}
}
for (int i = 0 ; i < n ; i++)
if (arr[i] < 0)
temp[j++] = arr[i];
memcpy(arr, temp, sizeof(temp));
}
int main()
{
int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
segregateElements(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout <<endl;
return 0;
}
|
73,074,752 | 73,074,860 | How can i call class function with its name in c++ | Problem: I have to call functions with its callee names in class. I tried function-pointer with map by return the pointer of functions in class, but it seemed that compiler doesn't allow me to do that with the error
'&': illegal operation on bound member function expression
I want to create a class with function bind with tis callee name ,so I run a register function in its constructor function, then I want to run the funcion inside the class with its callee name. I simplify the code with below,
#include <string>
#include <unordered_map>
class MyClass
{
typedef bool(*fun)(int num);
public:
MyClass() { MyClass_functionReg(); } // not sure if I can do this
~MyClass() {}
bool exec(std::string command)
{
fun function = find(command);
function(num);
return true;
}
private:
std::unordered_map<std::string, fun> v_map;
int num;
private:
bool MyClass_functionReg()
{
v_map.emplace("A", &a); // error here
v_map.emplace("B", &b);
v_map.emplace("C", &c);
v_map.emplace("ERROR", &c);
return true;
}
fun find(std::string command)
{
if (v_map.find(command) != v_map.end())
{
return v_map[command];
}
else
{
return v_map["ERROR"];
}
}
bool a(int num)
{
return true;
}
bool b(int num)
{
return true;
}
bool c(int num)
{
return true;
}
bool error(int num)
{
return true;
}
};
int main(int argc, char** argv)
{
MyClass t;
t.exec("A");
t.exec("B");
return true;
}
Is it just a syntax error? How can i fix this? Is there anything wrong with the way I implement this functionality?
| There are several issues in your code:
You need to use pointer to method for your fun type:
typedef bool(MyClass::*fun)(int num);
When adding the methods to the map, you need to add the class name qualifier, e.g.:
v_map.emplace("A", &MyClass::a);
When you invoke the method, you need to use the syntax for dereferencing a pointer to method:
(this->*function)(num);
See fixed version:
#include <string>
#include <unordered_map>
#include <iostream>
class MyClass
{
typedef bool(MyClass::*fun)(int num);
public:
MyClass() { MyClass_functionReg(); }
~MyClass() {}
bool exec(std::string command)
{
fun function = find(command);
(this->*function)(num);
return true;
}
private:
std::unordered_map<std::string, fun> v_map;
int num;
private:
bool MyClass_functionReg()
{
v_map.emplace("A", &MyClass::a); // error here
v_map.emplace("B", &MyClass::b);
v_map.emplace("C", &MyClass::c);
v_map.emplace("ERROR", &MyClass::c);
return true;
}
fun find(std::string command)
{
if (v_map.find(command) != v_map.end())
{
return v_map[command];
}
else
{
return v_map["ERROR"];
}
}
bool a(int num)
{
std::cout << "MyClass::a" << std::endl;
return true;
}
bool b(int num)
{
std::cout << "MyClass::b" << std::endl;
return true;
}
bool c(int num)
{
std::cout << "MyClass::c" << std::endl;
return true;
}
bool error(int num)
{
std::cout << "MyClass::error" << std::endl;
return true;
}
};
int main(int argc, char** argv)
{
MyClass t;
t.exec("A");
t.exec("B");
return 0;
}
Output:
MyClass::a
MyClass::b
A side note: main is returning an int (not bool). Returning 0 means there were no errors. See: What should main() return in C and C++?.
|
73,075,197 | 73,075,269 | How to call a function in C++? | so i tried making 2 functions and want to display both outputs and im new to C++
how do i fix this issue?
Code:
#include <iostream>
namespace first{
int x = 1;
}
namespace second{
int x = 2;
}
int main() {
using namespace first;
int x = 0;
std::cout << x << '\n';
std::cout << first::x << '\n';
std::cout << second::x << '\n';
return 0;
}
int lol() {
using namespace std;
using std::cout;
string lolipop = "hello world";
cout << lolipop << '\n';
return 0;
}
i want to display both outputs including hello world and the variables, variable are getting displayed in the output but not the second function the lol one.
| You need to call lol().
Example:
int lol(); // forward declaration
int main() {
using namespace first;
int x = 0;
std::cout << x << '\n';
std::cout << first::x << '\n';
std::cout << second::x << '\n';
lol(); // calling lol
return 0;
}
|
73,075,308 | 73,075,400 | why is it giving error stackoverflow back? | so i have been learning c++ for the past few days and now i have a task to make a Recursion and recursive function. i tried to solve it but it always gives this error back (Unhandled exception at 0x00535379 in cours.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00392FC4).)
or sometimes it gives the value of 1 of sum
any ideas for why?
int factorialNumber(int a,int b)
{
int sum;
if (b==a)
{
return b;
}
sum = a*b;
return sum + factorialNumber(b + 1,a);
}
void main(int sum)
{
int a=8,b=1;
factorialNumber(a,b);
cout <<a <<b<<endl<<sum;
system("pause>0");
}
| There are few other error in you code from C++ perspective, like invalid syntax for main, missing header, etc. But ignoring them for now to concentrate on factorial thing. You main error order of passing a and b to factorialNumber. Correcting it like below will work.
int factorialNumber(int a,int b)
{
int sum;
if (b==a)
{
return b;
}
sum = a*b;
return sum + factorialNumber(a,b + 1);
}
|
73,075,419 | 73,075,955 | How to convert CComBSTR to LPCSTR | I have CComBSTR in my code and have to pass it to function with argument type LPCSTR.
How to convert CComBSTR to LPCSTR?
| There are many ways to do this, but the ATL way would be using Using MFC MBCS/Unicode Conversion Macros:
void SomeCode()
{
USES_CONVERSION;
CComBSTR bstr(L"hello world");
LPCSTR lp = W2CA(bstr); // bstr is a LPWSTR
}
|
73,075,753 | 73,075,937 | C++ Creating Dynamic 2D Array With One Statement but Without auto | I've seen that a dynamic 2D array in C++ can be created as follows:
auto arr{ new int[nRows][nCols] };
nRows and nCols are compile-time known and the size of the array will not change during runtime.
I've tested what is the type of arr is PAx_i (where x is nCols). But I cannot figure out what to put instead of auto (if I don't want to use it) to create a dynamic 2D array with a single statement.
So, the question: Is it possible in C++ to specify the type of a dynamic 2D array directly (C-style like)? If yes, how?
| C++ does not support dynamically-sized raw arrays (aka Variable Length Arrays, or VLAs). Whenever you come across the need for such a dynamic array (how ever many dimensions it may have), you should be immediately thinking of using the std::vector container.
Once properly created, you can use the [] operator (concatenated, for 2-D vectors) in much the same way as you would with raw arrays.
Here's a short code demo that creates a dynamic, 2-dimensional 'array' of integers, using the std::vector class, and initializes all elements with an especially significant, non-zero value:
#include <iostream>
#include <vector>
int main()
{
size_t nCols, nRows;
std::cout << "Enter nRows and nCols: ";
std::cin >> nRows >> nCols;
if (nCols < 2 || nRows < 2) {
std::cout << "Matrix is too small!\n";
return 1;
}
// The following SINGLE LINE declares and initializes the matrix...
std::vector<std::vector<int>> arr(nRows, std::vector<int>(nCols, 42));
std::cout << "nRows = " << arr.size() << "\n";
std::cout << "nCols = " << arr[0].size() << "\n";
for (auto& row : arr) {
for (auto i : row) {
std::cout << i << " ";
}
std::cout << std::endl;
}
// Demo for how to use the "[][]" operator ...
arr[0][0] = arr[nRows - 1][nCols - 1] = 33; // Change 1st and last
std::cout << "------------\n";
for (auto& row : arr) {
for (auto i : row) {
std::cout << i << " ";
}
std::cout << std::endl;
}
return 0;
}
One of the great benefits of using std::vector over new[] is that you don't have to worry about subsequently calling delete[] – the container class takes care of all memory allocation and deallocation internally.
|
73,076,966 | 73,582,011 | SCIP - SCIPOptSuite - LNK2001 - unresolved external symbol | I am new to SCIP and I encounter this problem when I tried to build the branch-and-price framework I obtained from this link.
For your reference, I use MS Visual Studio 2019. I have downloaded and installed the precompiled packages. Then, I conducted the following steps in the property of the project I built in VS 2019.
C/C++ -> General -> Additional Include Directories -> C:\Program Files\SCIPOptSuite 8.0.1\include
Linker -> Input -> C:\Program Files\SCIPOptSuite 8.0.1\lib\libsoplex.lib
Then, I build the program, and many errors (LNK2001) appear, e.g. , unresolved external symbol _imp_SCIPaddCoefLinear, etc.
I have tried to put another library in the Linker, i.e.,
Linker -> Input -> C:\Program Files\SCIPOptSuite 8.0.1\lib\libscip.lib
But, the program raises another error saying the libscip.dll is not found and I am suggested to re-install the package to fix the problem.
I have also tried to reinstall the package, but I still do not have libscip.dll in the folder of SCIPOptSuite 8.0.1.
Do you have any suggestions for properly installing and using the SCIP framework in MS Visual Studio?
Thank you in advance.
| Obtained from @Richard Critten:
"...error saying the libscip.dll is not found ..." the directory containing libscip.dll need to be on the PATH or libscip.dll needs to be in the same directory as the executable.
|
73,077,061 | 73,081,039 | Can static polymorphism (templates) be used despite type erasure? | Having returned relatively recently to C++ after decades of Java, I am currently struggling with a template-based approach to data conversion for instances where type erasure has been applied. Please bear with me, my nomenclature may still be off for C++-natives.
This is what I am trying to achieve:
Implement dynamic variables which are able to hold essentially any value type
Access the content of those variables using various other representations (string, ints, binary, ...)
Be able to hold variable instances in containers, independent of their value type
Convert between variable value and representation using conversion functions
Be able to introduce new representations just by providing new conversion functions
Constraints: use only C++-11 features if possible, no use of libraries like boost::any etc.
A rough sketch of this might look like this:
#include <iostream>
#include <vector>
void convert(const std::string &f, std::string &t) { t = f; }
void convert(const int &f, std::string &t) { t = std::to_string(f); }
void convert(const std::string &f, int &t) { t = std::stoi(f); }
void convert(const int &f, int &t) { t = f; }
struct Variable {
virtual void get(int &i) = 0;
virtual void get(std::string &s) = 0;
};
template <typename T> struct VariableImpl : Variable {
T value;
VariableImpl(const T &v) : value{v} {};
void get(int &i) { convert(value, i); };
void get(std::string &s) { convert(value, s); };
};
int main() {
VariableImpl<int> v1{42};
VariableImpl<std::string> v2{"1234"};
std::vector<Variable *> vars{&v1, &v2};
for (auto &v : vars) {
int i;
v->get(i);
std::string s;
v->get(s);
std::cout << "int representation: " << i <<
", string representation: " << s << std::endl;
}
return 0;
}
The code does what it is supposed to do, but obvoiusly I would like to get rid of Variable::get(int/std::string/...) and instead template them, because otherwise every new representation requires a definition and an implementation with the latter being exactly the same as all the others.
I've played with various approaches so far, like virtual templated, methods, applying the CRDT with intermediate type, various forms of wrappers, yet in all of them I get bitten by the erased value type of VariableImpl. On one hand, I think there might not be a solution, because after type erasure, the compiler cannot possibly know what templated getters and converter calls it must generate. On the other hand I think i might be missing something really essential here and there should be a solution despite the constraints mentioned above.
| This is a classical double dispatch problem. The usual solution to this problem is to have some kind of dispatcher class with multiple implementations of the function you want to dispatch (get in your case). This is called the visitor pattern. The well-known drawback of it is the dependency cycle it creates (each class in the hierarchy depends on all other classes in the hierarchy). Thus there's a need to revisit it each time a new type is added. No amount of template wizardry eliminates it.
You don't have a specialised Visitor class, your Variable serves as a Visitor of itself, but this is a minor detail.
Since you don't like this solution, there is another one. It uses a registry of functions populated at run time and keyed on type identification of their arguments. This is sometimes called "Acyclic Visitor".
Here's a half-baked C++11-friendly implementation for your case.
#include <map>
#include <vector>
#include <typeinfo>
#include <typeindex>
#include <utility>
#include <functional>
#include <string>
#include <stdexcept>
struct Variable
{
virtual void convertValue(Variable& to) const = 0;
virtual ~Variable() {};
virtual std::type_index getTypeIdx() const = 0;
template <typename K> K get() const;
static std::map<std::pair<std::type_index, std::type_index>,
std::function<void(const Variable&, Variable&)>>
conversionMap;
template <typename T, typename K>
static void registerConversion(K (*fn)(const T&));
};
template <typename T>
struct VariableImpl : Variable
{
T value;
VariableImpl(const T &v) : value{v} {};
VariableImpl() : value{} {}; // this is needed for a declaration of
// `VariableImpl<K> below
// It can be avoided but it is
// a story for another day
void convertValue(Variable& to) const override
{
auto typeIdxFrom = getTypeIdx();
auto typeIdxTo = to.getTypeIdx();
if (typeIdxFrom == typeIdxTo) // no conversion needed
{
dynamic_cast<VariableImpl<T>&>(to).value = value;
}
else
{
auto fcnIter = conversionMap.find({getTypeIdx(), to.getTypeIdx()});
if (fcnIter != conversionMap.end())
{
fcnIter->second(*this, to);
}
else
throw std::logic_error("no conversion");
}
}
std::type_index getTypeIdx() const override
{
return std::type_index(typeid(T));
}
};
template <typename K> K Variable::get() const
{
VariableImpl<K> vk;
convertValue(vk);
return vk.value;
}
template <typename T, typename K>
void Variable::registerConversion(K (*fn)(const T&))
{
// add a mutex if you ever spread this over multiple threads
conversionMap[{std::type_index(typeid(T)), std::type_index(typeid(K))}] =
[fn](const Variable& from, Variable& to) {
dynamic_cast<VariableImpl<K>&>(to).value =
fn(dynamic_cast<const VariableImpl<T>&>(from).value);
};
}
Now of course you need to call registerConversion e.g. at the beginning of main and pass it each conversion function.
Variable::registerConversion(int_to_string);
Variable::registerConversion(string_to_int);
This is not ideal, but hardly anything is ever ideal.
Having said all that, I would recommend you revisit your design. Do you really need all these conversions? Why not pick one representation and stick with it?
|
73,077,170 | 73,077,288 | Why static upcast with virtual inheritance is always correct for GCC? | After learnt from :
Why can't static_cast be used to down-cast when virtual inheritance is involved?
I'm expecting following code give me the result that shows the static_cast is wrong and dynamic_cast is right.
#include <stdio.h>
class A {
public:
virtual ~A() {}
int a;
};
class B : public virtual A {
int b;
};
class C : public virtual A {
int c;
};
class D : public B, public C {
int d;
};
int main() {
D obj;
A* a1 = &obj;
A* a2 = (A*)&obj;
A* a3 = dynamic_cast<A*>(&obj);
A* a4 = static_cast<A*>(&obj);
C* c = &obj;
A* a5 = c;
A* a6 = (A*)(c);
A* a7 = dynamic_cast<A*>(c);
A* a8 = static_cast<A*>(c);
B* b = &obj;
A* a9 = b;
A* a10 = (A*)b;
A* a11 = dynamic_cast<A*>(b);
A* a12 = static_cast<A*>(b);
printf("D: %llx %llx %llx %llx %llx\n", &obj, a1, a2, a3, a4);
printf("C: %llx %llx %llx %llx %llx\n", c, a5, a6, a7, a8);
printf("B: %llx %llx %llx %llx %llx\n", b, a9, a10, a11, a12);
}
However, gcc 8/9 gives me following reuslt, showing both static cast and dynamic cast is correct:
D: 7ffddb098a80 7ffddb098aa0 7ffddb098aa0 7ffddb098aa0 7ffddb098aa0
C: 7ffddb098a90 7ffddb098aa0 7ffddb098aa0 7ffddb098aa0 7ffddb098aa0
B: 7ffddb098a80 7ffddb098aa0 7ffddb098aa0 7ffddb098aa0 7ffddb098aa0
So what's the magic involved here? How can I make a case that reproduce the static_cast problem?
Note:
gcc8 with -fdump-lang-class gives me following output:
Class D
size=48 align=8
base size=32 base align=8
D (0x0x7f0756155000) 0
vptridx=0 vptr=((& D::_ZTV1D) + 24)
B (0x0x7f0755f834e0) 0
primary-for D (0x0x7f0756155000)
subvttidx=8
A (0x0x7f075614c0c0) 32 virtual
vptridx=40 vbaseoffset=-24 vptr=((& D::_ZTV1D) + 104)
C (0x0x7f0755f83548) 16
subvttidx=24 vptridx=48 vptr=((& D::_ZTV1D) + 64)
A (0x0x7f075614c0c0) alternative-path
| Not sure, but it seems like you confuse upcasting with downcasting. In your code there are only upcasts, and those are fine. You get the expected compiler error for example with this:
D obj;
A* a4 = static_cast<A*>(&obj);
D* d = static_cast<D*>(a4);
gcc reports:
<source>: In function 'int main()':
<source>:26:28: error: cannot convert from pointer to base class 'A' to pointer to derived class 'D' because the base is virtual
26 | D* d = static_cast<D*>(a4);
| ^
If you remove the virtual inheritance in your example the static_cast would fail as well, because then the cast is ambiguous.
|
73,077,431 | 73,078,094 | How to customize function parameter errors(c++) | I wrote a function that requires two parameters, but I don't want those two parameters to be 0.
I want to make the compiler know that those two parameters cannot be 0 through some ways, otherwise the editor will report an error in the form of "red wavy line".
I refer to "custom exception class" to solve this problem, but I find this method does not work.
If there are someone knows how to do , I will be very happy, because it takes me a whole day
For example:
#include<iostream>
using namespace std;
int Fuction(int i , int j){
//code
}
int main(){
Funciton(1,1);
Funciton(0,0);
//I don't want i or j is zero
//But if they are still zero , The program will still work normally
return 0;
}
| There is no integer type without a 0. However, you can provoke a compiler error by introducing a conversion to a pointer type. Its a bit hacky, but achieves what you want (I think) for a literal 0:
#include <iostream>
struct from_int {
int value;
from_int(int value) : value(value) {}
};
struct non_zero {
int value;
non_zero(int*) = delete;
non_zero(from_int f) : value(f.value) {}
};
void bar(non_zero n) {
int i = n.value; // cannot be 0
}
int main() {
bar(non_zero(42));
//bar(non_zero(0)); // compiler error
}
bar is the function that cannot be called with a 0 parameter. 0 can be converted to a pointer but that constructor has no definition. Any other int will pick the other constructor. Though it requires the caller to explicitly construct a non_zero because only one user defined conversion is taken into account.
Note that this only works for a literal 0. There is no error when you pass a 0 to this function:
void moo(int x){
bar(non_zero(x));
}
Thats why it should be considered as a hack. Though, in general it is not possible to trigger a compiler error based on the value of x which is only known at runtime.
If you want to throw an exception, thats a whole different story. You'd simply add a check in the function:
if (i == 0) throw my_custom_exception{"some error message"};
|
73,077,492 | 73,077,613 | Does Python have the C++ equavalent of (var = value, var) | In C++ (and maybe C), you are able to do the following:
uint8_t one = 0;
if ((one = randomUint8t(), one) == 255){
printf("One has the max uint8_t value");
}
So you assign the value of the random uint8 function to one, and you return one to be used in the expression evaluation.
This particularly useful if you are trying to debug a while loop or if you want to assign a value to a variable unconditionally, but enter the if statement (or not) based on the new value of that same variable.
| This is possible since Python 3.8 with assignment expressions aka the "walrus" operator :=. Example:
import random
if (one := random.randint(0, 255)) == 255:
print("one == 255")
|
73,077,660 | 73,078,738 | Writing data order using boost::asio::async_write | I have two async write operations using boost::asio::async_write
boost::asio::async_write(socket, boost::asio::buffer(data1), function);
boost::asio::async_write(socket, boost::asio::buffer(data2), function);
Does boost guarantee that data will be written to the socket in the exact order in which the write operations were called? In this case, I need know, is data1 will be sent before data2?
If not, how can such an order be guaranteed?
|
Q. Does boost guarantee that data will be written to the socket in the exact order in which the write operations were called?
No, in fact it forbids this use explicitly:
This operation is implemented in terms of zero or more calls to the stream's async_write_some function, and is known as a composed operation. The program must ensure that the stream performs no other write operations (such as async_write, the stream's async_write_some function, or any other composed operations that perform writes) until this operation completes.
Q. In this case, I need know, is data1 will be sent before data2? If not, how can such an order be guaranteed?
You use a strand and chained operations (starting the next async operation from the completion handler of the first).
A flexible way to do that without requiring a lot of tedious code is to use a queue with outbound messages
You can look through my answers for examples
Alternatively using coroutines (asio::spawn or c++20's with asio::co_spawn) to hide the asynchrony:
async_write(socket, boost::asio::buffer(data1), use_awaitable);
async_write(socket, boost::asio::buffer(data2), use_awaitable);
(use yield_context for Boost Context based stackful coroutines when you don't have c++20)
Lastly, keep in mind you can write buffer sequences:
async_write(socket, std::array {
boost::asio::buffer(data1),
boost::asio::buffer(data2) }, function);
|
73,078,126 | 73,078,453 | Explicitly specify additional template arguments - But I have no arguments left to specify | The following code does not compile under clang (tested with version 10.0), but compiles under gcc (tested with version 10.1); C++ version 14.
Which of the compilers is correct?
template< typename T > int func(); // (1)
template< typename ... Args > int func(); // (2)
template<> int func<int>() { return 1; }
int main {
// func<int>(); // (*)
}
The error message of clang is:
function template specialization func ambiguously refers to more than one function template; explicitly specify additional template arguments to identify a particular function template
My problem is, the function marked with (1) does not have additional template parameters, thus I cannot add additional template parameters. So, how to solve this problem?
If I uncomment the line (*), then gcc also refuses to compile this code with the message:
call of overloaded func<int>() is ambiguous.
| The given program(even without the call) is not valid because you're trying to explicitly specialize function template func with information that is not enough to distinguish/disambiguate which func to specialize. A gcc bug report has been submitted here.
There are 2 ways to solve this depending on which func you want to specialize. Note also that the function call func<int>(); will still be ambiguous. The solution given below is just for specialization and not for call expression.
Method 1
My problem is, the function marked with (1) does not have additional template parameters, thus I cannot add additional template parameters. So, how to solve this problem?
In case, you want to explicitly specialize #1 you can solve the error by moving the explicit specialization above/before #2 as shown below:
template< typename T > int func(); // (1)
template<> int func<int>() { return 1; } //OK NOW, explicitly specialize #1
template< typename ... Args > int func(); // (2)
int main() {
}
Working demo
Method 2
And in case you want to explicitly specialize #2 you should add more template argument in specialization as shown below:
template< typename T > int func(); // (1)
template< typename ... Args > int func(); // (2)
template<> int func<int, double>() { return 1; } //OK NOW, explicitly specialize #2
int main() {
}
Working demo
|
73,079,238 | 73,081,086 | How to use a QTimer only after a QThread is started | I would like to use a QTimer in my MainWindow application. The timer should start when the thread is started. I have tried:
ct_thread.h
#include <QtCore>
#include <QThread>
#include <QTimer>
class CT_Thread : public QThread
{
Q_OBJECT
public:
explicit CT_Thread(QObject* parent = 0);
QTimer* timer;
void run();
private slots:
void on_timer();
};
ct_thread.cpp (Version 1)
#include "ct_thread.h"
#include "mainwindow.h"
#include <QtCore>
#include <QDebug>
CT_Thread::CT_Thread(QObject* parent) :
QThread(parent)
{}
void CT_Thread::run()
{
timer = new QTimer(0);
connect(timer, SIGNAL(timeout()), this, SLOT(on_timer()));
timer->start(1000);
// do something else
}
void CT_Thread::on_timer()
{
qDebug() << "Hello World!";
}
This does not reach the "Hello World!", i.e. the connection does not work properly.
Alternatively, I tried connecting in the constructor. This connects the Slot but the timer starts when opening the GUI and not when the user starts ct_thread.
ct_thread.cpp (Version 2)
CT_Thread::CT_Thread(QObject* parent) :
QThread(parent)
{
timer = new QTimer(0);
connect(timer, SIGNAL(timeout()), this, SLOT(on_timer()));
timer->start(1000);
}
void CT_Thread::run()
{
// do something else
}
void CT_Thread::on_timer()
{
qDebug() << "Hello World!";
}
What do I do wrong and how do I have to phrase it?
Thanks in advance!
| I'm assuming the timer should be handled within the thread.
You are missing an event loop in the thread. QThread can be implemented with or without event loop. A timer needs an event loop (it cannot just interrupt the code it currently executes in the thread and call the on_timer() method preemtively instead).
Calling exec() will run the event loop for the thread.
void CT_Thread::run()
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(on_timer()));
timer->start(1000);
// do something else
exec();
}
Note that I also gave the timer a parent to avoid a memory leak.
Note that a timer can also signal an event cross thread (thread affinity matters for that case). By default the thread affinity is the thread that created the object, therefore in your first example, the timer has the tread affinity set to the CT_Thread instance and will post it's event on the thread's event loop.
|
73,079,481 | 73,080,947 | How to access a variable from another class using Qt C++? | I've been trying to access another class variable, but I can't build the project. QtCreator doesn't show any error / alert. I'm trying to create a ToDo app as a University project and I need to access the name of the list to link the task to the list.
I'm sorry for this very simple question but I'm starting out both with C++ and Qt. I have already checked similar questions, but none of the answers work for me (100% my fault).
These are some code snippets:
ListManager.h
public:
static QStringList listName;
ListManager.cpp
void ListManager::on_pushButton_addList_clicked(){
QString nameList = QInputDialog::getText(this, tr("Add list"), tr("List name"), QLineEdit::Normal, tr("Untitled list"), &ok);
listName += nameList; // saves the name of the list in a QStringList
}
In the class TaskManager.cpp I want to access the names to set the QComboBox labels.
TaskManager.cpp
#include "listmanager.h"
// more code
void ListManager::on_pushButton_addTask_clicked(){
QStringList listsNames = ListManager::listName;
addTaskDialog.comboBox->addItems(listsNames);
}
As I mentioned before I don't get any error / alert by both QtCreator & CppCheck. When I try to build the program I get these issues:
error: Undefined symbols for architecture arm64:
"ListManager::listName", referenced from:
ListManager::on_pushButton_addList_clicked() in listmanager.o
TaskManager::on_pushButton_addTask_clicked() in taskmanager.o
error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [ToDoApp.app/Contents/MacOS/ToDoApp] Error 1
Any help would be much appreciated!
| To your ListManager.cpp add a line (usually it is placed before any method implementaton) like the following
QStringList ListManager::listName;
This will instantiate the static variable. The declaration in the header file is just a declaration, then you have to create it somewhere in the code.
If you don't istantiate the variable the compiler will not give you any error but the linker does because it is not able to find the real istance of the variable.
I'd like to add a suggestion: avoid where possible the use of static variables. It's better that the external object TaskManager holds a reference to ListManager and use a data member,
|
73,079,603 | 73,079,913 | How to make a custom header available system-wide with clang++? | EDIT
I have been educated about this topic and I have decided to close this question
P.S In the comments, can someone tell me how to close my question?
I have some simple C++ code here that I want to compile. I am currently on a mac with MacOS Big Sur running on my computer and I don't have the <bits/stdc++.h> file as a "default" header available for all cpp files. In order to add it I went in my /Library/Developer/CommandLineTools/usr/include/c++/v1 folder and made a bits folder with a stdc++.h file manually. However if I try to compile source code with this header included I get the following error:
test.cpp:1:10: fatal error: 'bits/stdc++.h' file not found
#include <bits/stdc++.h>
Here is my clang version as well:
Apple clang version 12.0.5 (clang-1205.0.22.11)
Target: x86_64-apple-darwin20.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
What I want to achieve
To compile the code successfully with my manually created bits/stdc++.h file. Preferably using clang++.
(If possible) Find a way to quickly do it.
What I've already tried
I've already found this thread with similar question asked, but it the answers provided didn't work for me.
I also Linking custom header files when compiling c++, but it seems irrelevant to my problem.
My source code
#include <bits/stdc++.h>
int main()
{
cout << "Meow Meow Meow\n";
return 0;
}
| First of all - it's greatly discouraged to use headers like stdc++.h.
If you anyway want to do that, you need to find the system directories your version of clang looks at. Run the following commands in the terminal:
% touch file.cpp
% clang++ -c file.cpp -v
At the bottom it should give you output like this:
#include <...> search starts here:
/usr/local/include
/Library/Developer/CommandLineTools/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1
/Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include
...
Just chose a directory you think is more suitable for you custom header and add whatever you want to be available for inclusion:
% cd /usr/local/include
% sudo mkdir bits && cd bits
% sudo touch stdc++.h
Now an include directive of form #include <bits/stdc++.h> should work with any cpp file compiled with clang. You only need to populate it with content.
|
73,079,900 | 73,080,083 | Is there any other option to decrease this piece of code time complexity? | In this code, I'm iterating over a graph of vertices and comparing the weights of each vertex and its neighbors to find the maximum weight between them. Then store the number of times a vertex is marked by its neighbor vertices in X[i].
map<double, list<double>> adjacency;
map<double, double> degree;
map<double, double> W;
map<double, double> X;
void find_max_w()
{
double max = 0.;
int idx_max;
for (const auto &pair : adjacency)
{
max = 0;
W.find(pair.first)->second > max ? max = W.find(pair.first)->second, idx_max = pair.first : max = max;
for (double d : pair.second)
{
W.find(d)->second > max ? max = W.find(d)->second, idx_max = d : max = max;
}
X.find(idx_max)->second += 1;
}
}
apparently, accessing to a map by value is time-consuming, and I have three of these :
W.find(pair.first)->second > max ? max = W.find(pair.first)->second, idx_max = pair.first : max = max;
W.find(d)->second > max ? max = W.find(d)->second, idx_max = d : max = max;
X.find(idx_max)->second += 1;
I was wondering if there is any other way to implement this more efficiently and less time-consuming? for example, other data structures?
| You can consider to replace one or more of your std::maps with std::unordered_maps.
The complexity for searching an item in std::map, using std::map::find is:
Logarithmic in the size of the container.
This is for worse case (since not mentioned otherwise).
On the other hand the complexity for searching an item in std::unordered_map, using std::unordered_map::find is:
Constant on average, worst case linear in the size of the container.
(emphasis is mine)
The performance of both options depends on your data and must be profiled in order to select between them.
On average a search in an unordered_map is faster (O(1)), but there are cases it deteriorates to linear (O(n)). map is slower on average, but gives you stable performance (O(logn)).
|
73,080,637 | 73,090,115 | OPENGL flickering on updating model uniform to same value | I have looked up almost all related questions regarding flickering in opengl. They all mostly have something to do with z-buffer or perspective projection. However, I'm rendering a single quad on screen that too without depth testing. I update model uniform every frame to the same value and then I get flickering. However if I have my object translate around the screen by updating uniform then it all works fine.
mat4 model = mat4_identity();
model = mat4_translatev(make_vec3(100.0f, 200.0f, 0.0f));
vec4 color = make_vec4(1.0f, 0.8f, 0.7f, 1.0f);
mat4 projection = mat4_ortho(0.0f, 800.0f, 600.0f, 0.0f, -1.0f, 1.0f);
Shader shader("generic_shader.vs", "generic_shader.fs");
shader.use();
//shader.set_vec4("color", &color);
shader.set_mat4("model", &model);
shader.set_mat4("projection", &projection);
float vertices[] = {
0.0f, 0.0f,
0.0f, 200.0f,
200.0f, 0.0f,
200.0f, 200.0f,
};
unsigned int indices[] = {
0, 1, 2,
2, 1, 3,
};
unsigned int vao, vbo, ebo;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glGenBuffers(1, &ebo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
while (!glfwWindowShouldClose(window))
{
float currentFrame = static_cast<f32>(glfwGetTime());
deltaTime = currentFrame - lastFrame;
while(deltaTime < REQUIRED_FRAME_TIME)
{
currentFrame = static_cast<f32>(glfwGetTime());
deltaTime = currentFrame - lastFrame;
}
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
processInput(window);
glDisable(GL_DEPTH_TEST);
glClearColor(1.0f, 0.5f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
shader.use();
//model = mat4_translatev(make_vec3(16.0f * currentFrame, 12.0f * currentFrame, 0.0f)); // <- if I uncomment this then it does not flicker
shader.set_mat4("model", &model);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glfwPollEvents();
glfwSwapBuffers(window);
}
This is what shader.use does
void Shader::use()
{
glUseProgram(this->program_id);
}
My matrices are column major and this is how the shader function sets the uniform
void Shader::set_mat4(const char* uniform_name, mat4* value)
{
*value = mat4_transpose(*value);
glUniformMatrix4fv(glGetUniformLocation(this->program_id, uniform_name), 1, GL_TRUE, &value->E[0][0]);
}
processInput() doesn't do anything. Consider it as an empty body function.
I'm using my own math library for vector and matrix operations. I trying to learn opengl and have made notes on things I have learned. I hope someone already familiar with how opengl works can help me understand what is happening here.
A gif depicting the flickering. Please note the flickering stops if I uncomment that one line in code as marked above.
Flickering GIF
| The problem is not with the OpenGL part of your code, but with the way how you transpose your model matrix.
The following code
*value = mat4_transpose(*value);
will override value with it's transposed representation, which means that every second frame the screen is rendered with a wrong matrix. Stop storing the result in value (use a local variable) and everything should work.
|
73,080,686 | 73,080,763 | Incorrect conversion from Raw RGB Depth image to gray | I am working with a simulation in Python equipped with a depth sensor. The visualization it's done in C++. The sensor gives me the following image that I need to convert to gray.
For the conversion, I have the next formula:
normalized = (R + G * 256 + B * 256 * 256) / (256 * 256 * 256 - 1)
in_meters = 1000 * normalized
For converting the image to gray in C++, I've written the following code:
cv::Mat ConvertRawToDepth(cv::Mat raw_image)
{
// raw_image.type() => CV_8UC3
// Extend raw image to 2 bytes per pixel
cv::Mat raw_extended = cv::Mat::Mat(raw_image.rows, raw_image.cols, CV_16UC3, raw_image.data);
// Split into channels
std::vector<cv::Mat> raw_ch(3);
cv::split(raw_image, raw_ch); // B, G, R
// Create and calculate 1 channel gray image of depth based on the formula
cv::Mat depth_gray = cv::Mat::zeros(raw_ch[0].rows, raw_ch[0].cols, CV_32FC1);
depth_gray = 1000.0 * (raw_ch[2] + raw_ch[1] * 256 + raw_ch[0] * 65536) / (16777215.0);
// Create final BGR image
cv::Mat depth_3d;
cv::cvtColor(depth_gray, depth_3d, cv::COLOR_GRAY2BGR);
return depth_3d;
}
Achieving the next result:
If I do the conversion in python, I can simply write:
def convert_raw_to_depth(raw_image):
raw_image = raw_image[:, :, :3]
raw_image = raw_image.astype(np.float32)
# Apply (R + G * 256 + B * 256 * 256) / (256 * 256 * 256 - 1).
depth = np.dot(raw_image, [65536.0, 256.0, 1.0])
depth /= 16777215.0 # (256.0 * 256.0 * 256.0 - 1.0)
depth *= 1000
return depth
Achieving the next result:
It's clear that in python it's done better, but the formula is the same, the image is the same, then why is it a difference and how can I rewrite the code in C++ to give me similar results as in Python?
| It looks like you are dealing with np.float32 array in Python while CV_8UC3 array in C++.
Try converting to CV_32FC3 before calculation.
// Convert to float and split into channels
cv::Mat raw_image_float;
raw_image.convertTo(raw_image_float, CV_32FC3);
std::vector<cv::Mat> raw_ch(3);
cv::split(raw_image_float, raw_ch); // B, G, R
|
73,080,945 | 73,081,004 | Provide definition of constructor template outside a class template | Consider the following class template with a constructor template:
template <class T>
class C{
public:
T val_;
std::string str_;
template <typename S>
C(const S& str);
// C(const S& str) : str_(str) {}; // Valid definition of constructor within class body
void print(){std::cout << str_;}
};
I'm, however, trying to define the constructor outside of the class, but I can't seem to figure out a way to account for the type S.
template <typename T, typename S> // incorrect as too many parameters
C<T>::C(const S& str) : str_(str) {};
Alternatively, I tried
template <typename T>
C<T>::C(const std::string& str) : str_(str) {};
which also does not work (and probably defeats the purpose of S)
How can I correctly define this constructor outside the class.
Does such a pattern (where class template parameters differ from constructor template parameters) serve any practical purpose? An example would be very helpful.
| The correct syntax is:
template <class T>
template <class S>
C<T>::C(const S& str)
{
// ...
}
Regarding your second question:
One example of using this pattern (of templating a ctor) is the way to achieve type-erasure in C++ using templates.
This article has some examples: https://quuxplusone.github.io/blog/2019/03/18/what-is-type-erasure/ (search for "templated constructor").
Or this 10 minutes clip that demonstrates it: https://www.youtube.com/watch?v=ZPk8HuyrKXU.
|
73,080,946 | 73,081,011 | How can I run .exe external application with C++ and VS? And continue execute my C++ code? | I solved it with command System(.. .exe);
And .exe application starts. But my VS C++ code stops and will continue only when I'll close started .exe application.
How can I continue my C++ code with opened and run .exe application?
| You can either fork your process, and start your application in the child process, or you can run a new thread which will block untill your application terminates.
|
73,081,412 | 73,081,486 | Can't access private constructor from a friend class | In the following code snippet, g++ compiler outputs the following error:
error: ‘B::B(const string&)’ is private within this context 857 |
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
Commenting out the line where smart pointers are used seem to work. However, I'm not sure why it works for the other cases, and still not work for the smart pointer case.
#include <memory>
#include <iostream>
#include "string"
class A;
class B
{
friend class A;
B(const std::string& dummyString) { std::cout << dummyString << std::endl; }
};
class A
{
public:
A()
{
B b("dummy1");
B* pB1 = new B("dummy2");
std::unique_ptr<B> pB2 = std::make_unique<B>("dummy3");
}
};
int main()
{
A a;
}
| The problem is that make_unique which is supposed to construct an instance of B is not a friend of B. Therefore it does not have access to B's private constructor.
You can use the following to achieve something similar:
std::unique_ptr<B> pB2 = std::unique_ptr<B>(new B("dummy3"));
In general it is advised to prefer make_unique to calling new yourself, and I do not encourage it in any way (see here: Differences between std::make_unique and std::unique_ptr with new).
But if you are bound to this specific class hirarchy it will solve your issue.
|
73,081,417 | 73,081,603 | Why there is linker error in this code even though the function body exist | I am not able to understand that why this code gives linker error. I have a project with these two files
myclass.cpp
class MyClass
{
public:
void SomeFun(){ ... } // SomeFun is defined here
};
main.cpp
class MyClass
{
public:
void SomeFun(); // SomeFun is declared here
};
int main()
{
MyClass obj;
obj.SomeFun(); // This throws undefined reference linker error during build. Why?
}
1: In Summary, I have a class "MyClass" with function "SomeFun" declared in main.cpp and defined in myclass.cpp. I expected the build to succeed since during linking stage it should have found the definition of SomeFun(). But it fails !
2: But why does it work fine if I just move the class declaration in lets say file "myclass.h" and include that header in both cpp ( with function body defined in myclass.cpp). How header file is making difference?
| This in myClass.cpp
class MyClass
{
public:
void SomeFun(){ ... } // SomeFun is defined here
};
Is a definition for MyClass. This in main.cpp
class MyClass
{
public:
void SomeFun(); // SomeFun is declared here
};
Is another definition of MyClass.
The one-definition-rule (ODR) states:
Only one definition of any variable, function, class type, enumeration type, concept (since C++20) or template is allowed in any one translation unit (some of these may have multiple declarations, but only one definition is allowed). )
[...]
Further...
There can be more than one definition in a program of each of the following: class type, enumeration type, inline function, inline variable (since C++17), templated entity (template or member of template, but not full template specialization), as long as all of the following is true:
each definition appears in a different translation unit
the definitions are not attached to a named module (since C++20)
each definition consists of the same sequence of tokens (typically, appears in the same header file)
[...]
If all these requirements are satisfied, the program behaves as if there is only one definition in the entire program. Otherwise, the program is ill-formed, no diagnostic required.
1: [...] But it fails !
It fails because its an ODR violation. The two definitions do not consist of the same sequence of tokens.
2: But why does it work fine if I just move the class declaration in lets say file "myclass.h" and include that header in both cpp
Because then there is only a single definition in your program. Also including the same header in different translation units is fine, because then all definitions do consist of the same sequence of tokens.
|
73,082,491 | 73,088,991 | operator[] - differentiate between get and set? | Are there any advances in recent C++ that allows for differentiating between getting and setting values via the operator[] of a class? (as Python does via __setitem__ and __getitem__)
const T& operator[](unsigned int index) const;
T& operator[](unsigned int index);
I am wrapping an std::unordered_map, and want to let my users access the data via the operator[], but also do some behind the scenes record-keeping to keep things aligned in my data structure.
Searching reveals a few answers, but they are all many years old, and I was wondering if C++ has added extra functionality in the meantime.
| Assume your wrapper class implements set and get methods that perform the appropriate record keeping actions. The wrapper class can then also implement operator[] to return a result object that will delegate to one of those methods depending on how the result is used.
This is in line with the first related question you identified (Operator[] C++ Get/Set).
A simple illustration is below. Note that a const map would not be able to call set_item anyway, so the const overload of operator[] calls get_item directly.
class MapType {
...
struct Result {
MapType &map_;
KeyType key_;
Result (MapType &m, KeyType k) : map_(m), key_(k) {}
operator const ValueType & () const {
return map_.get_item(key_);
}
ValueType & operator = (ValueType rhs) {
return map_.set_item(key_, rhs);
}
};
...
const ValueType & get_item (KeyType key) const {
/* ... record keeping ... */
return map_.at(key);
}
ValueType & set_item (KeyType key, ValueType v) {
/* ... record keeping ... */
return map_[key] = v;
}
...
Result operator [] (KeyType key) { return Result(*this, key); }
const ValueType & operator [] (KeyType key) const {
return get_item(key);
}
...
};
|
73,082,887 | 73,083,018 | std::replace - Compiler deduces a char type from const char* literal converted explicitly to string | I want to replace my buffer string from a value of "eof" to "\0" using std::replace.
std::string buffer = "eof";
std::replace(buffer.begin(), buffer.end(), std::string("eof"), std::string("\0"));
Compiler error :
no match for ‘operator==’ (operand types are ‘char’ and ‘const std::__cxx11::basic_string<char>’)
| The problem is that internally std::replace checks == on *first and old_value where first is the first argument passed(iterator here) and old_value is the third argument passed shown in the below possible implementation:
template<class ForwardIt, class T>
void replace(ForwardIt first, ForwardIt last,
const T& old_value, const T& new_value)
{
for (; first != last; ++first) {
//----------vvvvvv vvvvvvvvv--------->compares *first with old_value
if (*first == old_value) {
*first = new_value;
}
}
}
Now *first is char and old_value(and new_value) is std::string in our example and since there is no operator== for checking if a char and a std::string are equal and also as there is no implicit conversion between the two, we get the mentioned error.
One way to solve this is to use std::string::replace. More alternatives can be found at : Replace substring with another substring C++
|
73,083,214 | 73,083,239 | what does this line of syntax mean in c++? | this is a quick question, Im translating a program that's in C++ to C, and I saw this line of code,
for (int v : adj[u]) {
referenced in this article: link
and I am not really sure what it does. I tried googling it and got results for range based for loops in C++, but cannot find anything that has this exact syntax and what it means. Help would be much appreciated.
| It's a very simple for loop that iterates over the elements of adj[u], going 1 by 1.
|
73,083,485 | 73,117,968 | QTableView, select row and shift+click | I have a QTableview in an app, the selectionMode is set to QAbstractItemView::ExtendedSelection.
I have a button from which I select a specific row of the table view, using below call.
myTableView->selectRow(rowNumber);
The problem is, that if I have a row i selected. then press my button, row j is selected. Then when I then shift click another row k. The selection in the tableview will be from i->k, not j->k.
This question is essentially a duplicate of this question. But none of the discussed solutions work. The author in a comment on the accepted answer even says the accepted answer does not work.
I have tried calling the setCurrentIndex method before and after the selectRow method. But it made no change.
| Looks like you are facing similar issue to what you linked: you don't set current index together with selection change.
Small example to illustrate:
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QStringListModel model( { "First", "Second", "Third", "Fouth" });
auto p_view = new QTableView;
p_view->setModel(&model);
auto p_btn = new QPushButton("Select second row");
QObject::connect(p_btn, &QAbstractButton::pressed, [p_view]() {
p_view->selectRow(1);
p_view->setCurrentIndex(p_view->model()->index(1,0));
});
auto p_layout = new QHBoxLayout;
p_layout->addWidget(p_view);
p_layout->addWidget(p_btn);
QWidget main;
main.setLayout(p_layout);
main.show();
return app.exec();
}
Here row p_view->setCurrentIndex(p_view->model()->index(1,0)); will do the difference.
|
73,083,498 | 73,085,877 | Disable prevent windows log event | I'm using WMI (Windows Management Instrumentation) to try to collect some information from a allot of remote computers.
The issue is that every time I try to initiate a connection to a remote computer/resource using:
//IWbemLocator::ConnectServer method (wbemcli.h)
m_pLoc->ConnectServer ....
where
IWbemLocator *m_pLoc;
(You can assume m_pLoc is correctly initialized)
, if the remote resource is unavailable, Windows generates a log event in the Windows Event Viewer:
DCOM was unable to communicate with the computer ....using any of the
configured protocols; requested by PID .....
The problem is that given a huge number of remotes that at some point are not accessible the logs get flooded.
Is there any way to control or to prevent Windows from pushing a event in the Event Viewer every time I try to initiate a connection?
Seems that arguments for :
IWbemLocator::ConnectServer method (wbemcli.h)
or
CoCreateInstance used to intialize an IWbemLocator do not permit this sort of very custom configuration I'm looking for.
Any suggestion or alternatives?
Thank you!
| Looking at the message logged in EventViewer more closely, I can see that this is a DCOM thing, and it looks like you can turn DCOM error logging off by (as usual) tweaking the registry.
The key you want is:
HKEY_LOCAL_MACHINE
SOFTWARE
Microsoft
Ole
And then create a DWORD value in there called ActivationFailureLoggingLevel and set it to 2.
Info gleaned from here. I haven't tested this myself but it looks like it should work.
|
73,083,545 | 73,083,695 | About function declarations in functions | We can have function declarations inside of function bodies:
void f(double) {
cout << "f(double) called";
}
void f(int) {
cout << "f(int) called";
}
void g() {
void f(double); //Functions declared in non-namespace scopes do not overload
f(1); //Therefore, f(1) will call f(double)
}
This can be done in order to hide a function such as f(int) in this case, but my question is: Is this really the only reason why it is possible to declare a function inside of another?
Or in other words:
Does the possibility of declaring a function inside of a function exist for the sole purpose of hiding a function?
| This can also be used to limit the visibility of a function declaration to only one specific function. For example:
file1.cpp:
#include <iostream>
void f(double d) {
std::cout << d << '\n';
}
file2.cpp:
int main() {
void f(double);
f(1); // prints 1
}
void g() {
f(2); // error: 'f' was not declared in this scope
}
|
73,083,861 | 73,083,910 | No matching function compile error when passing lambda expression to a templated caller function? | Code:
#include <iostream>
template <class FunctorType>
void caller(const FunctorType& func) {
func();
}
int main() {
double data[5] = {5., 0., 0., 0., 0.};
auto peek_data = [data]() { std::cout << data[0] << std::endl; };
auto change_data = [data]() mutable { data[0] = 4.2; };
caller(peek_data); // This works
caller(change_data); // This doesn't
return 0;
}
If I compile this with clang++ -std=c++11 mutable_lambda.cpp, I got
error: no matching function for call to object of type 'const (lambda at mutable_lambda.cpp:8:22)'.
Question:
Why passing the second lambda expression with mutable copy capture failed to compile? Thanks in advance!
| A mutable lambda has a non-const operator(). You are trying to call this non-const operator() through a const reference. That doesn't work for the same reason that calling any non-const non-static member function doesn't work through a const reference.
If you want to allow caller to modify the passed function object (through a non-const operator() call) if it is passed as non-const argument, then take it by forwarding reference instead of const reference:
template <class FunctorType>
void caller(FunctorType&& func) {
func(); // maybe std::forward<FunctorType>(func)();
}
Also note that change_data does not change the data in main. It changes a copy of it stored inside the lambda. If you want it to change the data in main, you need to capture data by-reference and then the lambda itself also doesn't need to be mutable anymore:
auto change_data = [&data]() { data[0] = 4.2; };
|
73,084,516 | 73,115,307 | C++ printing unicode characters gives question marks | I want to start by saying I know how to print Unicode characters to console using _setmode(_fileno(stdout), _O_U16TEXT). The problem I have is with printing Unicode characters that are "non-standard". For example, when I try to print ▁ ▂ ▃ ▄ ▅ ▆ ▇ █ ▇ ▆ ▅ ▄ ▃ ▁ using wprintf, it returns this:
The project is set to "Unicode Character Set" and visual studio is showing the characters fine when showing them from file.
I found the answer and put it below
| From what I have found so far. there is no easy work around except for using another font which does include those characters. What I ended up doing was just editing the font using Fontlab. If anyone else ends up follow my footsteps. once you finish editing:
change the font name unless you want to overwrite the existing font (wouldn't recommend)
EXPORT AS TTF
I don't know why but when exporting as otf, the console shows the wrong characters.
|
73,085,423 | 74,020,681 | Is there an equivalent of submdspan for mdarray? | The repo of the exciting mdspan, a multi-dimensional analogue of std::span suggested for the C++ standard libraries, now also contains a reference implementation of the closely-related mdarray, which unlike mdspan owns its data.
But whereas the submdspan function can produce a subset of an mdspan, I can't find an analogue for mdarray. What I was expecting was a function that behaves exactly the same as submdspan and returns an mdspan, but which operates on an mdarray.
Is this planned but not implemented yet? If not, why not?
Edit:
I've temporarily solved it with a home-brew solution in the form of an overload of submdspan that takes an mdarray, then creates a temporary mdspan that maps to the entire mdarray, and calls submdspan on that.
It does the job for now! But I'm not confident this covers every conceivable mdarray, as there is almost no documentation at the moment. Would still love an answer to the original question.
template <class ElementType, class Extents, class LayoutPolicy, class... SliceSpecs>
auto submdspan(
mdarray<ElementType, Extents, LayoutPolicy> &arr,
SliceSpecs... slices)
{
return submdspan(
mdspan<ElementType, Extents, LayoutPolicy>(arr.data(), arr.mapping()),
slices...);
}
| Just randomly ran across this: since I am the primary author/maintainer on all involved things (mdspan, mdarray, submdspan and the reference implementation) yeah we can add that. And the way I would do that is actually calling the "to_mdspan" function of the mdarray, and call submdspan on that:
auto sub = submdspan(mda.to_mdspan(), slice_specifiers...);
In order for the two proposals to be independent I will keep that apart for now (unless LEWG tells me otherwise) and write a follow up paper which simply adds an overload to submdspan which does the above to forward to the overload taking an mdspan.
But generally: you can just open an issue on the repo to ask about proposal issues.
|
73,085,590 | 73,112,962 | Shuffle a 2D string array | I'm doing a C++ program, in which I want to shuffle an array (or part of an array). Here is the array:
string colorTheme[8][8] = {
{"blue", "blue", "green", "green", "violet", "violet", "teal", "teal"},
{"beige", "beige", "red", "red", "indigo", "indigo", "pink", "pink"},
{"cyan", "cyan", "yellow", "yellow", "orange", "orange", "azure", "azure"},
{"purple", "purple", "lime", "lime", "tangerine", "tangerine", "fuschia", "fuschia"},
{"brown", "brown", "gray", "gray", "black", "black", "white", "white"},
{"olive", "olive", "crimson", "crimson", "silver", "silver", "gold", "gold"},
{"maroon", "maroon", "coral", "coral", "plum", "plum", "ivory", "ivory"},
{"aqua", "aqua", "jade", "jade", "amber", "amber", "ruby", "ruby"}
};
If I wanted to shuffle the first n rows and n columns, how would I do it? Ideally, I would run
shuffle(n);
because colorTheme is in the same class as shuffle().
| The best way to tackle this problem is to convert the 2D array into 1D, as shuffling a 1D array is a lot simpler. Under the covers, create an int array shuffler; fill an int array with values from 0 - n^2 and shuffle them using something like rand. From there, use the values in the int array as new positions for your string array. Once you have shuffled your string array, convert it back into a 1D array. Here is a simple c++ source file I created (feel free to use).
#include <iostream>
#include <string>
using namespace std;
void shufflePos(int n, int arr[]);
void printArray(int *a, int length) {
cout << "[ ";
for (int i = 0; i < length; i ++) {
cout << a[i];
if (i != length - 1) {
cout << ", ";
}
}
cout << " ]\n";
}
void shufflePos(int n, int arr[]) {
for(int i = 0; i < n; i++) {
arr[i] = i;
}
// shuffle positions
srand(time(0));
for(int i = 0; i < (n - 2); i++) {
/*if(arr[i] != i) // i has already been swapped
continue;
*/
int tmp = arr[i];
// cout << "i = " << i << ", n - i = " << (n - i) << ", ";
int random = rand();
// cout << "random = " << random << ", ";
int nextPos = i + random % (n - i);
// cout << "nextPosition = " << nextPos << endl;
arr[i] = arr[nextPos]; // swap
arr[nextPos] = tmp;
}
//printArray(arr, n);
/* bool chck = check(arr, n);
if(chck == false)
cout << "FALSE" << endl;
else
cout << "TRUE" << endl; */
}
void swapString(string arr[], int pos1, int pos2) {
string tmp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = tmp;
return;
}
void shuffleString(string strs[], int len) {
int valArr[len];
shufflePos(len, valArr);
string to[len];
// copying values into another array
for(int i = 0; i < len; i++) {
to[i] = strs[valArr[i]];
}
// copying to[] into strs[]
for(int i = 0; i < len; i++) {
strs[i] = to[i];
}
}
int main() {
string colorTheme[8][8] = {
{"blue", "blue", "green", "green", "violet", "violet", "teal", "teal"},
{"beige", "beige", "red", "red", "indigo", "indigo", "pink", "pink"},
{"cyan", "cyan", "yellow", "yellow", "orange", "orange", "azure", "azure"},
{"purple", "purple", "lime", "lime", "tangerine", "tangerine", "fuschia", "fuschia"},
{"brown", "brown", "gray", "gray", "black", "black", "white", "white"},
{"olive", "olive", "crimson", "crimson", "silver", "silver", "gold", "gold"},
{"maroon", "maroon", "coral", "coral", "plum", "plum", "ivory", "ivory"},
{"aqua", "aqua", "jade", "jade", "amber", "amber", "ruby", "ruby"}
};
cout << "What size of array do you want?" << endl;
int i;
cin >> i;
int n = i * i; // length of 1D array
string darr[n]; // 1D array
for(int r = 0; r < i; r++) { // fill values of 1D array // rows
for(int c = 0; c < i; c++) { // columns
darr[(i * r + c)] = colorTheme[c][r];
}
}
cout << 1 << endl;
shuffleString(darr, n);
cout << 2 << endl;
// convert 1D array back into 2D array
for(int r = 0; r < i; r++) {
for(int c = 0; c < i; c++) {
colorTheme[c][r] = darr[(i * r) + c];
}
}
for(int r = 0; r < i; r++) { // rows
for(int c = 0; c < i; c++) { // columns
cout << ": " << colorTheme[c][r] << " ";
}
cout << endl;
}
}
|
73,086,234 | 73,086,624 | malloc.cpp not found, header IS included | I am aware of this question and its solution. Its solution (to include two header files listed below) is already in the code, so the post was unhelpful relative to my program.
I am working on an MFC program, using an old version of ZLib, specifically its 2005 version.
To practice with the zipping library, I attempted to use it with a regular C++ console program and it worked successfully (it added files correctly to a zip file).
Now, I am trying to add it in my MFC program. When pressing a button, a function is called and one of its jobs is to add files to a zip file. The thing is, it DOES work, but ONLY when the Run button is pressed, leaving the program to run on its own. The file is compressed successfully in the correct .zip file... HOWEVER, the issue comes from when I add a breakpoint and step through the program in the debugger.
Upon reaching the line: buf = (void*)malloc(size_buf); (found in the CMiniZip::OpenZip(const char* sOutFn) function within minizip.cpp file, if that helps or matters), I come across an error malloc.cpp not found. Strange, as both <stdlib.h> and <malloc.h> are both included as mentioned in the solution of the question linked at the start of this post.
My confusion (and my question) comes from this: why will the program run and compress files as expected when pressing the Run button, but not run when stepping through the program with the help of a breakpoint and the debugger. And why do both these methods work just fine in a non-MFC C++ console program?
Note: The files I zip and the zip folder itself are not touched at all by me while stepping through the program. I am simply clicking the Step Into button with the debugger. AND, this issue did not show up when adding a breakpoint and stepping through the regular C++ (non-MFC) program.
I am using Visual Studio C++ 17 Professional.
Any insight is appreciated, thank you in advance ! :D
| Turns out there is no issue at all.
C++ console programs are different from MFC here. Stepping through that line in a console program is the same as stepping OVER that line in MFC.
In MFC, you are actually given the option of seeing the assembly or rather, disassembly, code, by clicking a Disassembly option in the bottom half of the "error" page.
There is not issue. The malloc function is simply hidden.
And it would be better to change that ancient malloc and free to new and delete.
|
73,086,801 | 73,087,143 | Why explicit-ness of std::pair's heterogeneous "move"-constructor changed in C++17? | Pardon the convoluted title, and consider this code:
#include <memory>
#include <utility>
using X = std::unique_ptr<int>;
using A = std::pair<int, const X>;
using B = std::pair<int, X>;
static_assert(std::is_constructible<A, B>::value, "(1)"); // Ok.
static_assert(std::is_convertible<B, A>::value, "(2)"); // Rejected by GCC and Clang, in C++14 and before.
static_assert(std::is_constructible<const X, X>::value, "(3)"); // Ok.
static_assert(std::is_convertible<X, const X>::value, "(4)"); // Ok.
In short, the constructor of std::pair<int, const std::unique_ptr<int>> from an rvalue of type std::pair<int, std::unique_ptr<int>> is explicit in C++14, and implicit and C++17 and newer. Where does this difference come from?
Only libstdc++ and libc++ demonstrate this behavior. In MSVC's library, the constructor is always implicit.
Why was it explicit in C++14? I don't see anything relevant on cppreference (constructor (6)).
| The relevant constructors have not been explicit before C++17 either.
GCC and Clang in pre-C++17 mode are actually considering std::is_convertible<B, A>::value false because A's move constructor is implicitly deleted.
The move constructor is implicitly deleted, because a const std::unique_ptr cannot be moved or copied.
The move constructor is required to fulfill std::is_convertible<B, A>::value before C++17, because it tests whether a function of the form
A test() {
return std::declval<B>();
}
would be well-formed. The return statement copy-initializes the A return value from the operand and before C++17 copy-initialization always involved a conversion to a temporary of the target type if necessary, then followed by direct-initialization of the target from the temporary. That direct-initialization would use the move constructor of A. The move can be elided by the compiler, but the move constructor must still be usable.
Since C++17 mandatory copy elision applies and even conceptually the copy-initialization does not contain the direct-initialization via the move constructor anymore.
|
73,086,879 | 73,086,913 | const char* pointer handling (C++) | Hi everyone I have a simple task in C++:
-> writing a program that takes a string from user input and loops over the characters in the string via a pointer.
If I understand correctly, then a previously declared string name; variable can also be accessed via const char*, implying that I can declare a pointer in the following manner: const char *pName = &(name[0]);. When printing the pointer, however, not the memory address but the actual variable is displayed in the terminal (see my code below). This prevents me from incrementing the pointer (see for loop).
Filename: countchar.cpp
#include <iostream>
using namespace std;
int main() {
string name;
std::cout << "Provide a string." << endl;
std::cin >> name;
const char *pName = &(name[0]);
cout << pName << endl;
// further downstram implementation
// int len = name.length();
// for(int ii = 0; ii < len; ii++){
// std::cout << "iteration" << ii << "address" << pName << endl;
// std::cout << "Character:" << *pName << endl;
// (pName+1);
// }
return 0;
}
Terminal output:
$ g++ countchar.cpp -o count
$ ./count
$ Provide a string.
$ Test
$ Test
As I am a quite a noob in regard to C++ help and an explanation are both highly appreciated (No material found online that solves my problem). Thanks in advance!
| The operator << overloaded for a pointer of the type char * such a way that it outputs the string pointed to by the pointer.
So according to the assignment instead of these statements
const char *pName = &(name[0]);
cout << pName << endl;
you need to use a loop like
for ( const char *pName = &name[0]; *pName != '\0'; ++pName )
{
std::cout << *pName;
}
std::cout << '\n';
|
73,087,181 | 73,108,824 | Boost SML: respond to determination made in action | I am trying to use a Boost SML state machine to implement a "receiver". As an example, lets say the SM receives ints and is "done" when it gets to a certain number:
An "idle" state moves to a "reading" state on a "receive" event, accumulate the received data
If the limit is reached, terminate, or else keep reading
I have done this so far with a guard, gNotDone, which returns true if the capacity is not reached.
And then while reading, having passed the guard, actually process the data in the aReceive action.
#include <boost/sml.hpp>
#include <iostream>
namespace sml = boost::sml;
namespace {
struct eReceive {
int data;
};
struct sIdle{};
struct sReading{};
struct Context {
Context(const std::string& name, unsigned capacity):
name(name),
received(0),
capacity(capacity) {
}
std::string name;
unsigned received;
unsigned capacity;
};
struct SM {
auto operator()() const noexcept {
using namespace sml;
const auto gNotDone = [this] (const Context& ctx) -> bool {
return ctx.received < ctx.capacity;
};
const auto aReceive = [this] (const eReceive& e, Context& ctx) {
ctx.received += e.data;
std::cout << "Received " << e.data << ", so far: " << ctx.received << std::endl;
};
const auto aDone = [] {
std::cout << "Done (reach capacity)" << std::endl;
};
// clang-format off
return make_transition_table(
// Start reading
*state<sIdle> + event<eReceive> [gNotDone] / aReceive = state<sReading>
// Keeps reading until "done"
, state<sReading> + event<eReceive> [gNotDone] / aReceive
, state<sReading> + event<eReceive> / aDone = X
);
// clang-format on
}
};
} // namespace
int main() {
Context theContext("The context", 30);
sml::sm<SM> sm{theContext};
sm.process_event(eReceive{11});
sm.process_event(eReceive{22});
}
Try it here.
Received 11, so far: 11
Received 22, so far: 33
However, I don't feel this is quite right: it feels like the next state should somehow be determined by the aReceive action - if the limit was passed, move into the terminal state.
As it is, you'll only move into the terminal state after the next receive event.
It also doesn't feel right to "test" in guards if the event will pass the limit as this probably entails repeating the calculation (it's just a sum here, but it could be expensive).
What is the standard way in an SML state machine to decide the next state based on what happened with an event in the current state?
| I think that your state machine can described as follows:
sml doesn't support choice puseudo state (rhombus shape in the diagram) but we can use "normal" state instead.
The diagram use if/else branch from the choice pseudo state. But it doesn't supported in sml.
So I define gDone and gNotDone. It is the similar as defining == and != operators for the C++ class.
The code is updated as follows:
struct eReceive {
int data;
};
struct sReading{};
// choice pseudo state (UML 2.x)
// sml doesn't support choice pseudo state directly
// but we can use (normal) state.
struct psChoice{};
struct Context {
Context(const std::string& name, unsigned capacity):
name(name),
received(0),
capacity(capacity) {
}
std::string name;
unsigned received;
unsigned capacity;
};
// eReceive/aReceive [gDone]/aDone
// *-->sReading------------------->psChoice--------------->X
// A |
// | | [else] (=gNotDone)
// | |
// +-------------------------+
//
struct SM {
auto operator()() const noexcept {
using namespace sml;
const auto gDone = [] (const Context& ctx) -> bool {
return ctx.received >= ctx.capacity;
};
// sml doesn't support "else" guard. So I define it.
const auto gNotDone = [gDone] (const Context& ctx) -> bool {
return !gDone(ctx);
};
const auto aReceive = [] (const eReceive& e, Context& ctx) {
ctx.received += e.data;
std::cout << "Received " << e.data << ", so far: " << ctx.received << std::endl;
};
const auto aDone = [] {
std::cout << "Done (reach capacity)" << std::endl;
};
// clang-format off
return make_transition_table(
// From state Event Guard Action To state
*state<sReading> + event<eReceive> / aReceive = state<psChoice>
, state<psChoice> [gNotDone] = state<sReading>
, state<psChoice> [gDone ] / aDone = X
);
// clang-format on
}
};
All code is at https://cpp.godbolt.org/z/Mc9nYzMcr
|
73,087,452 | 73,093,141 | Why can't Clang get __m128's data by index in constexpr function | #include <cstddef>
#include <immintrin.h>
constexpr float get_data(__m128 a, std::size_t pos) {
return a[pos];
}
It works on GCC. I wonder is there any workaround to make it possible
| Regardless of constexpr, a[pos] is only valid as a GNU C extension, not portable to MSVC. Storing to an array, or C++20 std::bit_cast to a struct might work. bit_cast is constexpr-compatible, unlike other type-punning methods. Although I'd be worried about how efficiently that would compile across compilers for runtime-variable pos
bit_cast does compile ok with clang, and works in a constexpr function. But compiles inefficiently for GCC.
Correction: clang compiles this, but rejects it if called in a context that requires it to be constant-evaluated. note: constexpr bit_cast involving type '__attribute__((__vector_size__(4 * sizeof(float)))) float const' (vector of 4 'float' values) is not yet supported.
Other failed attempts with current clang in a constexpr context:
_mm_store_ps - not supported. Nor is *(__m128*)f = a; because it's a reinterpret_cast.
f[0] = vec[0] etc. initializers: no, even literal constant indexing of a GNU C native vector isn't supported in clang in constexpr.
union type punning: reading an inactive member not allowed in a constexpr context
_mm_cvtss_f32(vec) - non-constexpr function unusable, so no chance of using if constexpr for separate shuffles and returns.
Not-working answer, may work at some point in the future but not with clang trunk pre 15.0
#include <cstddef>
#include <immintrin.h>
#include <bit>
// portable, but inefficient with GCC
constexpr float get_data(__m128 a, std::size_t pos) {
struct foo { float f[4]; } s;
s = std::bit_cast<foo>(a);
return s.f[pos];
}
float test_idx2(__m128 a){
return get_data(a, 2);
}
float test_idxvar(__m128 a, size_t pos){
return get_data(a, pos);
}
These compile to decent asm on Godbolt, the same you'd get from clang with a[pos]. I used -O3 -march=haswell -std=gnu++20
# clang 14 -O3 -march=haswell -std=gnu++20
# get_data has no asm output; constexpr is like inline in that respect
test_idx2(float __vector(4)):
vpermilpd xmm0, xmm0, 1 # xmm0 = xmm0[1,0]
ret
test_idxvar(float __vector(4), unsigned long):
vmovups xmmword ptr [rsp - 16], xmm0
vmovss xmm0, dword ptr [rsp + 4*rdi - 16] # xmm0 = mem[0],zero,zero,zero
ret
Store/reload is a sensible strategy for a runtime-variable index, although vmovd / vpermilps would be an option since AVX introduced a variable-control shuffle that uses dword indices. An out-of-range index is UB so the compiler doesn't have any requirement to return any specific data in that case.
Using vpermilpd for the constant index 2 is a waste of code-size vs. vmovhlps xmm0, xmm0, xmm0 or vunpckhpd. It costs a longer VEX prefix and an immediate, so 2 bytes of machine-code size, but otherwise same performance on most CPUs.
Unfortunately GCC doesn't do such a good job
We get a store/reload even for the fixed index of 2, and even worse, reload by bouncing through a GP-integer register. This is a missed optimization, but IDK how quickly it would get fixed if reported. So if you're going to do this, perhaps #ifdef __clang__ or #ifdef __llvm__ for bit_cast, and #ifdef __GNUC__ for a[pos]. (Clang defines __GNUC__ so check for that after special-casing clang.)
# gcc12 -O3 -march=haswell -std=gnu++20
test_idx2(float __vector(4)):
vmovaps XMMWORD PTR [rsp-24], xmm0
mov rax, QWORD PTR [rsp-16]
vmovd xmm0, eax # slow: should have loaded directly from mem
ret
test_idxvar(float __vector(4), unsigned long):
vmovdqa XMMWORD PTR [rsp-24], xmm0
vmovss xmm0, DWORD PTR [rsp-24+rdi*4] # this is fine, same as clang
ret
Interestingly the runtime-variable version didn't have the same anti-optimization for GCC.
|
73,087,819 | 73,088,136 | For loop not incrementing only when qInfo looks for array value | #include <QCoreApplication>
int ages[4] = {23,7,75,1000};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qInfo() << ages;
for (int i = 0; i < 5; i++){
qInfo() << i;
}
a.exec();
return 0;
}
returns:
0x7ff7d01f3010 0 1 2 3 4
To the terminal
But
#include <QCoreApplication>
int ages[4] = {23,7,75,1000};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qInfo() << ages;
for (int i = 0; i < 5; i++){
qInfo() << i;
qInfo() << ages[i];
}
a.exec();
return 0;
}
returns:
4713 0 4714 0 4715 0 4716 0 4717 0 4718
etc. to the terminal.
As a beginner this behavior is not intuitive and I do not understand what the difference is.
The first code was my attempt to see if my for loop was written incorrectly, but it acts as expected.
| You have undefined behaviour in your code because you are indexing the array out of its size. Your array has four elements, but you seem to try to access 5 elements in its. So, the last iteration is undefined behaviour.
You could write this instead:
#include <QCoreApplication>
int ages[4] = {23,7,75,1000};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qInfo() << ages;
for (int age : ages)
qInfo() << age;
a.exec();
return 0;
}
Depending on your compiler, you could use the sanitizer options to catch these, for example:
-fsanitize=undefined
I personally use these in my projects:
if (CMAKE_CXX_COMPILER_ID MATCHES "(Clang|GNU)")
add_compile_options(-Wall -Wpedantic -Wextra -Werror)
add_compile_options(-fsanitize=address -fsanitize=undefined -fno-omit-frame-pointer)
add_link_options(-fsanitize=address -fsanitize=undefined -fno-omit-frame-pointer)
elseif (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
set_property(DIRECTORY APPEND PROPERTY COMPILE_OPTIONS "/w")
endif()
add_compile_definitions(QT_DISABLE_DEPRECATED_BEFORE=0xFFFFFF)
I would also like to point out that you should use size_t instead of int for the loop counter as a good practice.
It is also worth pointing out that you should avoid using raw arrays in a C++, and especially Qt program. There are better choices, like:
std::array
std::vector
QList
etc.
Furthermore, you could even merge these two lines:
a.exec();
return 0;
Into the following (this is how it is typically written):
return a.exec();
|
73,088,437 | 73,088,736 | The next prime number | Among the given input of two numbers, check if the second number is exactly the next prime number of the first number. If so return "YES" else "NO".
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int nextPrime(int x){
int y =x;
for(int i=2; i <=sqrt(y); i++){
if(y%i == 0){
y = y+2;
nextPrime(y);
return (y);
}
}
return y;
}
int main()
{
int n,m, x(0);
cin >> n >> m;
x = n+2;
if(n = 2 && m == 3){
cout << "YES\n";
exit(0);
}
nextPrime(x) == m ? cout << "YES\n" : cout << "NO\n";
return 0;
}
Where is my code running wrong? It only returns true if next number is either +2 or +4.
Maybe it has something to do with return statement.
| I can tell you two things you are doing wrong:
Enter 2 4 and you will check 4, 6, 8, 10, 12, 14, 16, 18, ... for primality forever.
The other thing is
y = y+2;
nextPrime(y);
return (y);
should just be
return nextPrime(y + 2);
Beyond that your loop is highly inefficient:
for(int i=2; i <=sqrt(y); i++){
Handle even numbers as special case and then use
for(int i=3; i * i <= y; i += 2){
Using a different primality test would also be faster. For example Miller-Rabin primality test:
#include <iostream>
#include <cstdint>
#include <array>
#include <ranges>
#include <cassert>
#include <bitset>
#include <bit>
// square and multiply algorithm for a^d mod n
uint32_t pow_n(uint32_t a, uint32_t d, uint32_t n) {
if (d == 0) __builtin_unreachable();
unsigned shift = std::countl_zero(d) + 1;
uint32_t t = a;
int32_t m = d << shift;
for (unsigned i = 32 - shift; i > 0; --i) {
t = ((uint64_t)t * t) % n;
if (m < 0) t = ((uint64_t)t * a) % n;
m <<= 1;
}
return t;
}
bool test(uint32_t n, unsigned s, uint32_t d, uint32_t a) {
uint32_t x = pow_n(a, d, n);
//std::cout << " x = " << x << std::endl;
if (x == 1 || x == n - 1) return true;
for (unsigned i = 1; i < s; ++i) {
x = ((uint64_t)x * x) % n;
if (x == n - 1) return true;
}
return false;
}
bool is_prime(uint32_t n) {
static const std::array witnesses{2u, 3u, 5u, 7u, 11u};
static const std::array bounds{
2'047u, 1'373'653u, 25'326'001u, 3'215'031'751u, UINT_MAX
};
static_assert(witnesses.size() == bounds.size());
if (n == 2) return true; // 2 is prime
if (n % 2 == 0) return false; // other even numbers are not
if (n <= witnesses.back()) { // I know the first few primes
return (std::ranges::find(witnesses, n) != std::end(witnesses));
}
// write n = 2^s * d + 1 with d odd
unsigned s = 0;
uint32_t d = n - 1;
while (d % 2 == 0) {
++s;
d /= 2;
}
// test widtnesses until the bounds say it's a sure thing
auto it = bounds.cbegin();
for (auto a : witnesses) {
//std::cout << a << " ";
if (!test(n, s, d, a)) return false;
if (n < *it++) return true;
}
return true;
}
And yes, that is an awful lot of code but it runs very few times.
|
73,088,690 | 73,088,967 | How to use QGeoCoordinate in Qt C++ , especially the azimuthTo() and distanceTo() objects? | This is my code:
After specifying two different coordinates (geo and geo2), how can I know the distance between them using distanceTo()
//enter code here
QGeoCoordinate geo;
geo.setLatitude(90);
geo.setLongitude(90);
QGeoCoordinate geo2;
geo2.setLatitude(53.213456);
geo2.setLongitude(-9.182547);
edit:
I have read the documentation but still unable to figure out the right way.
| As per the documentation, it is a simple call of taking one of the two QGeoCoordinate objects and pass the other object to its member function.
So your code becomes:
QGeoCoordinate geo;
geo.setLatitude(90);
geo.setLongitude(90);
QGeoCoordinate geo2;
geo2.setLatitude(53.213456);
geo2.setLongitude(-9.182547);
qreal distanceInMeters = geo.distanceTo(geo2);
|
73,088,871 | 73,088,958 | Are 'volatile' and 'side effect' related? | Just a beginner question.
In the code from cppreference.com, there is a comment saying, "make sure it's a side effect" on the line using std::accumulate.
What is the author's intention in saying this? Is it related to the volatile int sink? (Maybe it means something like "make sure the sink is not optimized by the compiler"?)
Why volatile for sink? I think almost every compiler might know the std::accumulate will change the value of sink.
I thought I knew what volatile and "side-effect" meant, but maybe I'm missing some point!
#include <iostream>
#include <iomanip>
#include <vector>
#include <numeric>
#include <chrono>
volatile int sink;
int main()
{
std::cout << std::fixed << std::setprecision(9) << std::left;
for (auto size = 1ull; size < 1000'000'000ull; size *= 100) {
// record start time
auto start = std::chrono::system_clock::now();
// do some work
std::vector<int> v(size, 42);
// This is the line I mentioned.
sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect
// record end time
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> diff = end - start;
std::cout << "Time to fill and iterate a vector of " << std::setw(9)
<< size << " ints : " << diff.count() << " s\n";
}
}
| Not necessarily.
C++ has the 'as if' rule. The compiler must generate code that works 'as if' the source code was executed, but it doesn't have to do everything that the source code does, in exactly the same order.
Now look at the sink variable. After the line you mention it's never used again. So it's value has no visible effect on the program. So why should the compiler bother calculating it's value? Because of the as if rule it is perfectly legal for the compiler not to do so.
But there are a few exceptions to the as if rule, and one of them is volatile variables. Reads and writes to volatile variables must occur in exactly the way that the source code says. That's why volatile is important in this code. It forces the compiler to execute the std::accumulate call even though it has no visible effect on the program.
Further reading https://en.cppreference.com/w/cpp/language/as_if
|
73,089,019 | 73,089,144 | Cannot infer template argument 'T' when a second parameter includes 'T' | Given this template function:
template <
typename T,
typename U,
typename = std::enable_if<
std::is_same_v<U, std::unique_ptr<T>> ||
std::is_same_v<U, std::shared_ptr<T>>>>
T foo(U val) {
if constexpr (std::is_same_v<U, std::unique_ptr<T>>) {
return *val;
}
return *val;
}
I want to call it like this:
int x = foo(std::make_unique<int>(1));
But, it's giving this error:
Candidate template ignored: couldn't infer template argument 'T'
I can fix it by providing the type T explicitly:
int x = foo<int>(std::make_unique<int>(1));
Is it possible to fix it such that it can infer? The type is clearly embedded in the typename U but it does not seem to "propagate" to T.
| SFINAE constraints don't affect template argument deduction. Your compiler has to deduce T and U first, without even looking at your enable_if_t<...>.
I'd do something like this:
#include <memory>
#include <type_traits>
namespace impl
{
template <typename A, template <typename...> typename B>
struct specialization_of : std::false_type {};
template <template <typename...> typename T, typename ...P>
struct specialization_of<T<P...>, T> : std::true_type {};
}
template <typename A, template <typename...> typename B>
concept specialization_of = impl::specialization_of<A, B>::value;
template <typename T>
requires specialization_of<T, std::unique_ptr> || specialization_of<T, std::shared_ptr>
auto foo(T val)
{
if constexpr (specialization_of<T, std::unique_ptr>)
{
return *val;
}
return *val;
}
[I also want] std::is_same_v<U, std::function<T()>>
Then you need a specialized template just for this task. Something like:
template <typename T, typename U>
struct foo : std::false_type {};
template <typename T, typename U>
struct foo<std::function<T()>, U> : std::is_same<T, U> {};
Then foo<std::function<int()>, int> is true.
|
73,089,421 | 73,089,442 | Why can't we assign the value to a non-initialized string within a for loop in c++? | I'am learning c++ and I've a question like why can't we initalize a given string in a for loop.
string s, result;
cin >> s;
for(int i=0; i<s.length(); i++){
result[i] = s[i];
}
cout << result;
There simply won't be cout ofcourse. Because result string never got initialized in a for loop? Please explain why?
The following code, instead will be execute
result = s;
| result has the length 0 so using the subscript operator to dereference and assign any element (except assigning \0 to the terminating \0) has undefined behavior.
If you want to append a char to the string:
result += s[i];
|
73,089,542 | 73,089,589 | C++: Finding average for each salesperson from a text file | I need to calculate the average sales for each salesperson from a text file. My code will produce the correct output as the sample, but will not work if I add more information to the file without manually modifying the code.
I'm completely stuck on this, tried many different methods that I know but they doesn't completely satisfy the question. This is what I have so far.
Edit:
Is there a way to read the file, then add together all the amount that have the same name?
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
class Sales
{
public:
int id;
string name;
int salesCount = 1;
double salesAmount;
double avgSalesAmount;
};
void read()
{
int i = 0;
Sales sale[4];
fstream read;
read.open("Sales.txt");
while(!read.eof())
{
read.ignore();
getline(read, sale[i].name);
read >> sale[i].salesAmount;
if (sale[i].name == sale[i-1].name)
{
sale[i-1].salesAmount = sale[i-1].salesAmount + sale[i].salesAmount;
sale[i-1].salesCount++;
sale[i].salesCount = 0;
}
i++;
}
read.close();
for (int x = 0; x < 4; x++)
{
if (sale[x].salesCount != 0)
{
sale[x].avgSalesAmount = sale[x].salesAmount / sale[x].salesCount;
cout << sale[x].name << endl;
cout << sale[x].salesCount << endl;
cout << sale[x].avgSalesAmount << endl;
}
}
}
int main()
{
read();
return 0;
}
Sample file "Sales.txt":
Matthew
123.45
Matthew
432.15
Brown
89.95
Cook
500.00
Sample Output: https://i.stack.imgur.com/QS6jE.png
Current Output (No Formatting): https://i.stack.imgur.com/QTA7K.png
| This is caused by the static person count in your code, please try to replace the 4 with a larger constant.
const int PERSON_COUNT = 100;
void read()
{
int i = 0;
Sales sale[PERSON_COUNT];
fstream read, read2;
read.open("Sales.txt");
while(!read.eof())
{
read.ignore();
getline(read, sale[i].name);
read >> sale[i].salesAmount;
if (sale[i].name == sale[i-1].name)
{
sale[i-1].salesAmount = sale[i-1].salesAmount + sale[i].salesAmount;
sale[i-1].salesCount++;
sale[i].salesCount = 0;
}
i++;
}
read.close();
for (int x = 0; x < PERSON_COUNT; x++)
{
if (sale[x].salesCount != 0)
{
sale[x].avgSalesAmount = sale[x].salesAmount / sale[x].salesCount;
cout << sale[x].name << endl;
cout << sale[x].salesCount << endl;
cout << sale[x].avgSalesAmount << endl;
}
}
}
Note that using the variable-length array (VLA) in your functions is not recommended practice in most cases since it's a non-standard extension that doesn't work in all implementations. Please consider using std::vector<int> or other dynamic array solutions.
EDIT:
As Ted Lyngmo suggests, the code above is almost never the correct solution if the input amount is unknown during your coding period. But I'd keep that because it will need little effort for you to fix it if your scenario is simple enough.
Below is my humble refactor for you as a clearer solution. Hope this can enlighten you to build a better program on it.
#include <fstream>
#include <iomanip>
#include <ios>
#include <iostream>
#include <vector>
using namespace std;
class Sales {
public:
int id;
string name;
int salesCount = 1;
double salesAmount;
double avgSalesAmount;
};
void read() {
vector<Sales> sale;
ifstream fin("Sales.txt");
int i = 0;
string name;
double salesAmount;
while (fin >> name) {
fin >> salesAmount;
if (sale.empty() || sale.back().name != name) {
sale.push_back(Sales{i++, name, 1, salesAmount, 0});
} else {
sale.back().salesCount++;
sale.back().salesAmount += salesAmount;
}
}
fin.close();
for (auto &s : sale) {
s.avgSalesAmount = s.salesAmount / s.salesCount;
cout << s.name << endl;
cout << s.salesCount << endl;
cout << fixed << setprecision(2) << s.avgSalesAmount << endl;
cout << "---" << endl;
}
}
int main() {
read();
return 0;
}
test case:
A
1.00
A
2.00
A
3.00
B
2.00
B
3.00
C
4.00
A
3
2.00
---
B
2
2.50
---
C
1
4.00
---
EDIT 2:
If your data doesn't guarantee that records of the same person will come up in a row, in the simplest solution, please refer to std::map and use std::map<std::string, Sale> records to retrieve the person's record.
|
73,089,920 | 73,091,007 | game of stacks in which number is removed from top until it amounts to greater that given max sum | I'm trying to solve this hacker rank problem, which gives us two integer stacks and a maxSum variable assigned to a particular value and asks us to find total number of elements removed from top from both the stacks until sum of all number removed from stacks does not become greater than the given maxSum.
example;
stack 1 is; 4 2 4 6 1
stack 2 is; 2 1 8 5
maxSum=10
output=4 as we can remove 4,2,2, 1 & 4+2+2+1=9 which is less than 10.
I used below approach to implement my function to solve it and according to me everything in my code looks fine, but still i'm unable to pass many of the testcases. Kindly looking for help.
ps: i'm beginner in DSA.
int twoStacks(int maxSum, vector<int> a, vector<int> b) {
int count=0;
int sum=0;
int i=0;
int j=0;
while(sum<=maxSum){
if(i<a.size() && j<b.size() && sum+min(a[i],b[j])<=maxSum){
sum+=min(a[i],b[j]);
count++;
if(min(a[i],b[j])==a[i]){
i++;
}
else{
j++;
}
}
else if(i>=a.size() && j<b.size() && sum+b[j]<=maxSum){
sum+=b[j];
count++;
j++;
}
else if(i<a.size() && j>=b.size() && sum+a[i]<=maxSum){
sum+=a[i];
count++;
i++;
}
else{
break;
}
}
return count;
}
| Your code assumes that there is a "greedy" approach to ensure you find the maximum possible number of removals. But this is not true. It is not always best to take the minimum value among the two stack tops. For example, stack B could start with a rather great value, but have many small values after it, which would make it interesting to still take that first great value and then profit from the many subsequent values you can take from it:
maxSum: 10
A: {5, 5, 5, 5}
B: {6, 1, 1, 1, 1, 1, 1}
Your algorithm would take twice from A, while it is better to take 5 times from B.
So first take as many as possible from A, and if you can take them all, also continue taking as many from B. This represents one possible solution.
Then continue to take one less value from A and see if you then can take more from B. This again represents a potential solution. Continue this process until either no elements from A can be returned to it, or all values of B have been taken.
Among all potential solutions keep track of the most removals that could be done.
Code:
int twoStacks(int maxSum, vector<int> a, vector<int> b) {
int i = 0;
int j = 0;
int maxTakes = 0;
// Take as many as possible from A
while (i < a.size() && maxSum >= a[i]) {
maxSum -= a[i++];
}
while (true) {
// Take as many as possible from B
while (j < b.size() && maxSum >= b[j]) {
maxSum -= b[j++];
}
maxTakes = max(maxTakes, i + j);
if (i == 0 || j >= b.size()) return maxTakes;
// Return one value back to A so to make room for more from B
maxSum += a[--i];
}
return maxTakes;
}
|
73,090,139 | 73,090,489 | static member std::function of template class gets empty despite initalization | Consider the following class:
template <class T>
struct Test
{
Test() {
if (!f) {
f = []() { std::cout << "it works\n"; };
initialized = true;
}
}
static void check() {
if (f) f();
else std::cout << "f is empty\n";
}
T x{};
inline static std::function<void()> f;
inline static bool initialized = false;
};
An object of such class, if declared globally (Yes, I know it's a bad practice to use global variables), seems to empty the function f after it is initalized. The following example demonstrates this:
Test<double> t;
int main()
{
t.x = 1.5;
std::cout << "t.x = " << t.x << "\n";
std::cout << std::boolalpha << "initalized: " << Test<double>::initialized << "\n";
Test<double>::check();
return 0;
}
This prints:
t.x = 1.5
initalized: true
f is empty
I expected Test<double>::check(); to print it works.
However, the above example works as expected, when I do either of the following:
declare t within main()
do not use template for Test (just replace T with double for example)
make f and check() be not static
use plain function pointer instead of std::function
Does anyone know why this happens?
| The problem is related to the order of initialization of static variables which I guess is solved differently for the templated instantiated static variables compared to Test<double> on different compilers.
inline static Holder f;
is a static variable, so somewhere before entering main it will be default initialized (to an empty function). But Test<double> is another static variable that will get its own initialization before entering main.
On GCC it happens that
Test<double> is called
Test<double>::f is set by the constructor of Test<double>
the default constructor of Test<double>::f is called, thus emptying the function
This all happens inside __static_initialization_and_destruction_0 GCC method, if you actually use a wrapper object to break on static initialization of the variable you can see what's happening: https://onlinegdb.com/UYEJ0hbgg
How could the compiler know that you plan to set a static variable from another static variable before its construction? That's why, as you said, using static variables is a bad practice indeed.
|
73,090,157 | 73,090,806 | How to use library fmt with clang | My code is like
#include "fmt/compile.h"
int main() {
using namespace fmt::literals;
auto result = fmt::format("{}"_cf, FMT_VERSION);
printf("%s", result.data());
}
It cannot compile with clang. The compilation result can be seen here
How can I make it work with clang. thx
| Build of fmt depends on a bunch of macros. Here, build fails because operator () ""_cf is not defined in the clang version. If you look at the code you'll see it depends on macro FMT_USE_NONTYPE_TEMPLATE_ARGS for whatever reason.
Probably godbolt at inclusion of fmt doesn't declare the macro to be true for clang.
Regardless, if you simply add the line #define FMT_USE_NONTYPE_TEMPLATE_ARGS true before including fmt the code will compile on clang too. This is not recommended solution, the macro should be defined at build level, not directly in the code.
|
73,090,519 | 73,090,679 | what does vector<int> dist(n, INT_MAX); mean in C++? | i am new to C++ and I was wondering what the below code does. I tried googling but could not find the answer. Thanks
vector<int> dist(n, INT_MAX);
| The line of code serves to declare a variable called dist, and to initialise it is a std::vector object.
The <int> part of the vector initialisation is called a template argument. The std::vector class is templated, which means it can store any arbitrary data-type, which is why the type has to be declared within angled brackets <>.
As mentioned in the comments, n and INT_MAX are values being passed to one of the constructors of the std::vector. It is only one of the constructors, since there are various different overloads of the constructor (check out the documentation in the comments to your question to read about the different available constructors).
Function (and also method) overloading is when you declare various functions with the same name, but that differ in the number and/or types of parameters that can be passed to them (the return type can also vary).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.