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 |
|---|---|---|---|---|
71,916,926 | 71,917,143 | C++: How to specify types inside a tuple based on types inside another tuple? | Say I have a tuple type e.g.
using Tuple1 = std::tuple<int, float, double>;
and some templated class
template <typename T>
class DummyClass;
and that I want to specify a tuple type that looks like this
using Tuple2 = std::tuple<DummyClass<std::tuple_element<0, Tuple1>::type>,
DummyClass<std::tuple_element<1, Tuple1>::type>,
DummyClass<std::tuple_element<2, Tuple1>::type>>;
Only now I'd like to make the above more generic and not have to manually unroll all the types in Tuple2. Is this achievable via template metaprogramming / variadic logic?
| Do you mean sth like this?
#include <tuple>
#include <type_traits>
using t1=std::tuple<int,char,float>;
template <typename T>
struct S;
template<typename...Args>
std::tuple<S<Args> ...> maket2(const std::tuple<Args...>&);
template <typename T>
using t2 = decltype(maket2(std::declval<T>()));
static_assert(std::is_same_v<
t2<t1>,
std::tuple<S<int>, S<char>, S<float>>
>);
https://godbolt.org/z/K6KGKzo18
It uses the "classical" meta programming, maybe it can be also achieved using more contemporary constructs.
|
71,917,284 | 71,917,332 | What is this "operator" block of code in c++ class | I'm using someone's class for bitmaps, which are ways of storing chess positions in 64-bit bitsets. I was wondering what the part with auto() operator does. Is "auto" used because it returns one bit, which is why a return-type isn't specified for the function? I get that it checks that x and y are in the bounds of the chess board, and asserts an error if they aren't. I also understand that it returns a bit that corresponds to the x,y value pair for the bitset. I also don't get why the function is defined like it is, with an extra pair of parentheses. Any help is appreciated!
class BitBoard {
private:
std::bitset<64> board;
public:
auto operator()(int x, int y) {
assert(0<=x && x<=7);
assert(0<=y && y<=7);
return board[8*y+x];
}
}
};
| The "extra" pair of parentheses are because you're defining operator(), which lets instances of your class behave like functions. So if you had a:
BitBoard board;
you could get the value for x=3, y=5 by doing:
board(3, 5)
instead of having a method you call on the board explicitly, like board.get_bit_at(3, 5).
The use of auto just means it deduces the return type from std::bitset<64>'s operator[]; since the method isn't const qualified, this means it's just deducing the std::bitset::reference type that std::bitset's operator[] uses to allow mutations via stuff like mybitset[5] = true;, even though you can't give "true" references to single bits. If reimplemented a second time as a const-qualified operator(), e.g.:
auto operator()(int x, int y) const {
assert(0<=x && x<=7);
assert(0<=y && y<=7);
return board[8*y+x];
}
you could use auto again for consistency, though it doesn't save any complexity (the return type would be bool in that case, matching std::bitset's const-qualified operator[], no harder to type than auto).
The choice to use operator() is an old hack for multidimensional data structures to work around operator[] only accepting one argument; rather than defining operator[] to return a proxy type (which itself implements another operator[] to enable access to the second dimension), you define operator() to take an arbitrary number of arguments and efficiently perform the complete lookup with no proxies required.
|
71,918,003 | 71,918,060 | Is there a problem with how I am calling the member functions? | Write a program with a class called Dice in a file called "Dice.h" that has as a member object a vector that simulates the rolling of a single die a hundred times. as well as a member variable called Size which contains the size of the vector.
In the file Dice.cpp, the Dice class should have the following public member functions defined:
a default constructor which sets all of the values of the vector member object to 0.
roll100() which rolls the die 100 times and records that roll in the vector member object.
calculateRolls() which calculates the number of 1 rolls, the number of 2 rolls, the number of 3 rolls, the number of 4 rolls, the number of 5 rolls, and the number of 6 rolls. The function then displays the number of the respective rolls to the user.
printDice() which displays the contents of the vector to the screen with 10 elements of the vector per line for 10 lines.
https://i.stack.imgur.com/QaYHG.png
https://i.stack.imgur.com/v6gxj.png
https://i.stack.imgur.com/CzijH.png
Main.cpp:
#include <iostream>
#include "Dice.h"
#include <vector>
using namespace std;
int main() {
Dice roll;
roll.roll100();
roll.calculateRolls();
roll.printDice();
}
Dice.cpp:
#include "Dice.h"
#include <iostream>
#include <vector>
using namespace std;
Dice::Dice() {
vector <int> rolls(SIZE, 0);
}
const int SIZE = 100;
vector <int> rolls(SIZE, 0);
int ones;
int twos;
int threes;
int fours;
int fives;
int sixes;
void roll100() {
unsigned seed = time(0);
srand(seed);
int result;
for (int i = 0; i < SIZE; i++) {
result = (rand() % 6 + 1);
rolls[i] = result;
}
}
void calculateRolls()
{
for (int i = 0; i < SIZE; i++) {
if (rolls[i] == 1)
ones++;
if (rolls[i] == 2)
twos++;
if (rolls[i] == 3)
threes++;
if (rolls[i] == 4)
fours++;
if (rolls[i] == 5)
fives++;
if (rolls[i] == 6)
sixes++;
}
cout<<"Number of 1 rolls "<<ones<<"\n";
cout<<"Number of 2 rolls "<<twos<<"\n";
cout<<"Number of 3 rolls "<<threes<<"\n";
cout<<"Number of 4 rolls "<<fours<<"\n";
cout<<"Number of 5 rolls "<<fives<<"\n";
cout<<"Number of 6 rolls "<<sixes<<"\n";
}
void printDice() {
for (int i = 0; i < SIZE; i++) {
if (i % 9 == 0)
cout << endl;
cout << rolls[i];
}
}
Dice.h:
#ifndef DICE_H
#define DICE_H
#include <vector>
using namespace std;
class Dice {
private:
public:
const int SIZE = 100;
int ones;
int twos;
int threes;
int fours;
int fives;
int sixes;
Dice();
void roll100();
void calculateRolls();
void printDice();
};
#endif
| Dice.cpp needs
Dice::calculateRolls(){....}
etc
PS. I did not look for any other errors, just your given compile errors.
|
71,918,023 | 71,918,738 | Using omp parallel for in multiplication algorithm (BigInt multiplication) | For educational purpose I'm developing c++ library for operating with large numbers represented as vectors of chars (vector<char>).
Here is algorithm that I am using for multiplication:
string multiplicationInner(CharVector a, CharVector b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
IntVector stack(a.size() + b.size() + 1);
int i, j;
for (i = 0; i < a.size(); i++)
for (j = 0; j < b.size(); j++)
stack[i + j] += charToInt(a[i]) * charToInt(b[j]);
for (int i = 0; i < stack.size(); i++) {
int num = stack[i] % 10;
int move = stack[i] / 10;
stack[i] = num;
if (stack[i + 1])
stack[i + 1] += move;
else if (move)
stack[i + 1] = move;
}
CharVector stackChar = intVectorToCharVector(&stack);
deleteZerosAtEnd(&stackChar);
reverse(stackChar.begin(), stackChar.end());
return charVectorToString(&stackChar);
};
This function is called billion times in my program, so I would like to implement #pragma omp parallel for in it.
My question is: How can i parallelize first cycle?
This is what I have tried:
int i, j;
#pragma omp parallel for
for (i = 0; i < a.size(); i++) {
for (j = 0; j < b.size(); j++)
stack[i + j] += charToInt(a[i]) * charToInt(b[j]);
}
Algorithm stops working properly.
Advice needed.
Edit:
This variant works, but (with omp parallel for) benchmark shows it is 15x-20x slower than without it. (CPU: M1 Pro, 8 cores)
#pragma omp parallel for schedule(dynamic)
for (int k = 0; k < a.size() + b.size(); k++) {
for (int i = 0; i < a.size(); i++) {
int j = k - i;
if (j >= 0 && j < b.size()) {
stack[k] += charToInt(a[i]) * charToInt(b[j]);
}
}
}
This is part of my program, where multiplication is called most often. (Miller-Rabin test)
BigInt modularExponentiation(BigInt base, BigInt exponent, BigInt mod) {
BigInt x = B_ONE; // 1
BigInt y = base;
while (exponent > B_ZERO) { // while exponent > 0
if (isOdd(exponent))
x = (x * y) % mod;
y = (y * y) % mod;
exponent /= B_TWO; // exponent /= 2
}
return (x % mod);
};
bool isMillerRabinTestOk(BigInt candidate) {
if (candidate < B_TWO)
return false;
if (candidate != B_TWO && isEven(candidate))
return false;
BigInt canditateMinusOne = candidate - B_ONE;
BigInt s = canditateMinusOne;
while (isEven(s))
s /= B_TWO;
for (int i = 0; i < MILLER_RABIN_TEST_ITERATIONS; i++) {
BigInt a = BigInt(rand()) % canditateMinusOne + B_ONE;
BigInt temp = s;
BigInt mod = modularExponentiation(a, temp, candidate);
while (temp != canditateMinusOne && mod != B_ONE && mod != canditateMinusOne) {
mod = (mod * mod) % candidate;
temp *= B_TWO;
}
if (mod != canditateMinusOne && isEven(temp))
return false;
}
return true;
};
| Your loops do not have the proper structure for parallelization. However, you can transform them:
for (k=0; k<a.size()+b.size(); k++) {
for (i=0; i<a.size(); i++) {
j=k-i;
stack[k] += a[i] * b[j];
}
Now the outer loop has no conflicts. Look at this as a "coordinate transformation": you're still traversing the same i/j row/column space, but now in new coordinates: k/i stands for diagonal/row.
Btw, this code is a little metaphorical. Check your loop bounds, and use the right multiplication. I'm just indicating the principle here.
|
71,918,038 | 71,918,105 | C++ Program Returning Differing Results in IDEs and differing results when running the same data | I am trying to solve the following problem:
Farmer John has acquired a set of N (2 <= N <= 2,000) touchy cows
who are conveniently numbered 1..N. They really hate being too close
to other cows. A lot.
FJ has recorded the integer X_i,Y_i coordinates of every cow i (1
<= X_i <= 100,000; 1 <= Y_i <= 100,000).
Among all those cows, exactly two of them are closest together. FJ
would like to spread them out a bit. Determine which two are closest
together and print their cow id numbers (i) in numerical order.
10 | . . . . . . . 3 . . . . .
9 | . 1 . . 2 . . . . . . . .
8 | . . . . . . . . . . . . .
7 | . . . . . . . . . . 4 . .
6 | . . . . . . 9 . . . . . .
5 | . 8 . . . . . . . . . . .
4 | . . . . . 7 . . . . . . .
3 | . . . . . . . . . 5 . . .
2 | . . . . . . . . . . . . .
1 | . . . . 6 . . . . . . . .
0 ---------------------------
1 1 1 1
0 1 2 3 4 5 6 7 8 9 0 1 2 3
Quick visual inspection shows that cows 7 and 9 are closest together
(the distance separating them is sqrt(11+22) = sqrt(5), so the
output would be '7 9' on a single line (without quotes, of course).
Below is my coded attempt to solve the problem:
using namespace std;
int main() {
int n; cin >> n;
long long xcord[n],ycord[n];
for (int i=0; i<n; i++) {
cin >> xcord[i];
cin >> ycord[i];
}
long long shortest = 9999999999999;
int a=-1, b=-1;
for (int i=0; i<n; i++) {
for (int j=i+1; j<=n; j++) {
long long curDist = (xcord[i]-xcord[j])*(xcord[i]-xcord[j]) + (ycord[i]-ycord[j])*(ycord[i]-ycord[j]);
// cout << curDist << " ";
if (curDist < shortest) {
shortest = curDist;
a=i+1, b=j+1;
}
}
}
cout << a << " " << b << endl;
}
Here is the test case I am running:
25
24804 7918
98983 95075
10819 48641
84481 33476
56724 20854
83193 17014
72997 5394
69263 33045
26810 75288
85442 47243
81678 82129
84199 35206
68212 77035
62113 87896
49538 1375
145 90953
58175 62546
73175 5853
7789 37961
18883 49418
78257 90342
2048 64282
49057 95081
89406 47329
9778 68104
When I run the test case using my code, I get the correct answer, 7 18. I am running the code using VSCode. When I try running the code using replit, I get a completely different answer despite the test case being the same and when I try running the same test case over and over in replit, the program returns differing answers. Do you know why I am getting this error? Thanks a lot!
| Right here you go out of bounds on your array
for (int j = i + 1; j <= n; j++)
-----------------------^
that should be
for (int j = i + 1; j < n; j++)
now gives 7 18
|
71,918,116 | 71,918,179 | How to handle private members of a base class when implementing copy control in C++? | Given a Teacher class that derives from a Faculty class, how would I handle the name of a Teacher object, which is defined as a private member in Faculty but not in Teacher, for copy control?
// example code for the two classes
class Faculty{
public:
/* constructor
copy constructor
destructor
assignment operator
*/
string get_name() const{
return name;
private:
string name;
};
class Teacher : public Faculty{};
Assuming that Faculty class has a functioning copy control
// Copy constructor
Teacher(const Teacher& rhs) : Faculty(rhs){
name = rhs.name;
}
This line doesn't compile because it tries to access a private member of Faculty. Is this line needed or is the name of the copy already set to rhs.name by the initialization list, Faculty(rhs)? Would name be accessible if I directly define a string name in the private field of Teacher?
// Assignment operator
Teacher& operator=(const Teacher& rhs){
Faculty::operator=(rhs);
if(this != &rhs){
name = rhs.name; // same issue
}
return *this;
}
Same issue as copy control, is this needed or is the name already changed to rhs.name by the Faculty class's assignment operator?
|
Is this line needed or is the name of the copy already set to rhs.name
by the initialization list, Faculty(rhs)?
No the line is not needed (assuming a default or properly implemented Faculty copy constructor). The Faculty constructor will assign or initialise name for you properly.
Would name be accessible if I directly define a string name in the
private field of Teacher?
Yes, kind of. But it will be an entirely separate instance of name. You don't want to do this. You only want name defined once.
|
71,918,187 | 71,920,023 | Replace every letter with its position in the alphabet for a given string | The first step, I changed the string to a lowercase, after that I removed all the non letters from the string, now I am struggling to replace each letter with the alphabet position.
does anyone know how to do such a thing?
Thank you!
string alphabet_position(string message){
string alphabet= "abcdefghijklmnopqrstuvwxyz";
int aplha_numbers[100];
for_each(message.begin(), message.end(), [](char & c){
c = ::tolower(c);
});
for(int i=0; i< message.size(); i++){
if(message[i] < 'a' || message[i] > 'z'){
message.erase(i, 1);
i--;
}
}
for(int j=0; j<message.size(); j++){
int index = alphabet.find(message[j]);
aplha_numbers[j]= index +1;
}
std::ostringstream os;
for(int z: aplha_numbers){
os<<z;
}
std::string str(os.str());
return str;
}
Now I have a different issue , I am getting the alphabet positions but I also get a lot of garbage values after the last letter.
As an example Input: abc
output 123 and after that a lot of numbers 32761004966.....
| There are a few issues in your code:
Your main bug was that in this line:
for (int z : aplha_numbers)
You go over all the 100 elements in the allocated array, not just the valid entries.
In my solution there's no need for such an array at all. The stringstream objec is updated directly.
The position of a lower case character c is simply c-'a'+1. No need for a lookup table (at least assuming ascii input).
There's no need to actually change the input string by making it a lower case. This can be done on the fly as you traverse it.
Here's a complete fixed version:
#include <string>
#include <sstream>
#include <iostream>
#include <cctype>
std::string alphabet_position(std::string message)
{
std::ostringstream os;
for (auto const & c : message)
{
char c_lower = std::tolower(c);
if (c_lower < 'a' || c_lower > 'z') continue;
int pos = c_lower - 'a' + 1;
os << pos;
}
return os.str();
}
int main()
{
std::string s_in = "AbC";
std::string s_out = alphabet_position(s_in);
std::cout << "in:" << s_in << ", out:" << s_out << std::endl;
return 0;
}
Output:
in:AbC, out:123
A side note: it's better to avoid using namespace std;. See here: Why is "using namespace std;" considered bad practice?
|
71,919,058 | 71,919,255 | How do I change where the dll dependencies are located for an application after building? | I am new to creating applications with Visual Studio and C++, and I am working on my first project. I couldn't find any answers on exactly what I was looking for, but maybe I didn't see something I should have - when a project solution has been built, and created into an exe, it has dependent DLLs in that same directory. Is there any specific way to change this to make the dependent DLLs appear in a subfolder inside that directory (ie. $(SolutionDir)Releases/Dependencies instead of $(SolutionDir)Releases)? Thanks in advance.
| You can change the Output Directory in project properties. For example:
$(SolutionDir)$(Platform)\$(Configuration)\Dependencies
|
71,919,220 | 71,919,462 | LinkedList Insert Issue | I was trying to code insert in linkedlist for position 0 (i.e. the beginning of the linked list) and for other positions (like in between any two nodes and at the end of the linkedlist). The code is given below. But it seems to be not working as expected. Please let me know as to what I am doing wrong here.
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
void displayLL(Node *p)
{
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
}
Node *createLL(int A[], int n, Node *ll)
{
Node *tmp, *last;
ll = new Node;
ll->data = A[0];
ll->next = NULL;
last = ll;
for (int i = 1; i < n; i++)
{
tmp = new Node;
tmp->data = A[i];
tmp->next = NULL;
last->next = tmp;
last = tmp;
}
return ll;
}
int countNodesLL(Node *p)
{
int count = 0;
while (p != NULL)
{
count++;
p = p->next;
}
return count;
}
void InsertNodeLL(Node *p, int index, int value)
{
Node *tmp;
if (index < 0 || index > countNodesLL(p))
{
return;
}
tmp = new Node;
tmp->data = value;
// This should insert in the beginning of the Linked List - but it is not working.
if (index == 0)
{
tmp->next = p; // pointing next of tmp to p node
p = tmp; // making tmp as the HEAD of linkedList
}
// This inserts after 1st node, in between two nodes and at the end of the LL
else
{
for (int i = 0; i < index - 1; i++)
{
p = p->next;
}
tmp->next = p->next;
p->next = tmp;
}
}
int main(int argc, char const *argv[])
{
Node *linkedList = NULL;
int A[] = {1, 2, 3, 4, 5, 6, 7, 8};
linkedList = createLL(A, 8, linkedList);
displayLL(linkedList);
cout << endl;
InsertNodeLL(linkedList, 0, 15);
displayLL(linkedList);
cout << endl;
InsertNodeLL(linkedList, 4, 10);
displayLL(linkedList);
return 0;
}
I am getting the below output:
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 10 5 6 7 8
Expected Output:
1 2 3 4 5 6 7 8
15 1 2 3 4 5 6 7 8
15 1 2 3 4 10 5 6 7 8
Please help me as to what is wrong in the code.
| You made two mistakes, first you didn't return a value back to the linked list since you passed the pointer by value, and second in your insert function you also do not return a value as well you are modifying the head variable so you lose the previous values. Also you want to insert at the 5th position not the 4th. When you make the changes inside the function you are only using local variables so after the stack frame gets popped your linked list doesn't get updated. You can use a global variable instead but if you are passing by value you have to return back to the caller if you wish to change the list in main. Here is my reimplementation of your code: `
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
void displayLL(Node* p)
{
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
}
Node* createLL(int A[], int n, Node* ll)
{
Node* tmp, * last;
ll = new Node;
ll->data = A[0];
ll->next = NULL;
last = ll;
for (int i = 1; i < n; i++)
{
tmp = new Node;
tmp->data = A[i];
tmp->next = NULL;
last->next = tmp;
last = tmp;
}
return ll;
}
int countNodesLL(Node* p)
{
int count = 0;
while (p != NULL)
{
count++;
p = p->next;
}
return count;
}
Node* InsertNodeLL(Node* p, int index, int value)
{
Node* tmp;
Node* tmp2;
if (index < 0 || index > countNodesLL(p))
{
return 0;
}
tmp = new Node;
tmp->data = value;
// This should insert in the beginning of the Linked List - but it is not working.
if (index == 0)
{
tmp->next = p; // pointing next of tmp to p node
p = tmp;
return p; // making tmp as the HEAD of linkedList
}
// This inserts after 1st node, in between two nodes and at the end of the LL
else
{
tmp2 = p;
for (int i = 0; i < index - 1; i++)
{
tmp2 = tmp2->next;
}
tmp->next = tmp2->next;
tmp2->next = tmp;
return p;
}
}
int main(int argc, char const* argv[])
{
Node* linkedList = NULL;
int A[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
linkedList = createLL(A, 8, linkedList);
displayLL(linkedList);
cout << endl;
linkedList = InsertNodeLL(linkedList, 0, 15);
displayLL(linkedList);
cout << endl;
linkedList = InsertNodeLL(linkedList, 5, 10);
displayLL(linkedList);
return 0;
}
`
|
71,919,251 | 71,935,965 | Why `std::thread()` and `std::packaged_task()` works different, although they both accept callable targets? | Here is a simple code snippet:
#include <thread>
#include <future>
#include <functional>
void foo(int){}
int main()
{
std::thread(foo, 1).join(); //works indeed
std::packaged_task<void(int)> task{foo, 1}; //complian
std::packaged_task<void(int)> task{std::bind(foo, 1)};
}
Both std::thread() and std::packaged_task() accept callable targets, why the code for std::packaged_task() is a little different? Why does not make the std::packged_task() works like std::thread()(i.e. accepts arguments like std::thread)?
The class template std::packaged_task wraps any Callable target
(function, lambda expression, bind expression, or another function
object) so that it can be invoked asynchronously. Its return value or
exception thrown is stored in a shared state which can be accessed
through std::future objects.
| std::packaged_task does not run a function/callable immediately, a function execution is deferred and parameters can be passed later to void operator()( ArgTypes... args );, therefore the possible constructor template< class Function, class... Args > explicit packaged_task( Function&& f, Args&&... args ); is not necessary.
However std::thread runs a function/callable immediately, thus parameters must be passed to the constructor template< class Function, class... Args > explicit thread( Function&& f, Args&&... args );. You may consider it like sugar to avoid persistently writing code like std::thread(bind(f, 1)); instead of convenient std::thread(f, 1);.
|
71,920,326 | 71,922,176 | Why does ignore() before getline() take one less character input? | I am using the getline() function in C++, but there is a problem that the input starts from the second character. I used the ignore() function to erase what remains in the buffer first, emptying the buffer and receiving input. How can I empty the buffer and receive input properly?
Above is the execution result. I previously used the ignore() function and the getline() function to empty the buffer and receive input because there may be some leftovers in the buffer before.
In other programs that write like that, it also receives integer input before.
void InputValue(string *st) {
//cin.clear();
cin.ignore();
getline(cin, *st);
}
int main(void) {
string str;
InputValue(&str);
cout << str;
return 0;
}
| In the beginning, immediately after input, stdin (your input buffer) contains :
abcd
Those character are waiting to be extracted in whatever manner you choose. Since you are reading from stdin (using std::cin) using getline() from the stream into a std::string, getline() will consume all characters in the line, reading and discarding the trailing '\n' with all characters stored in your std::string. There are no characters left in stdin that need to be extracted using std::cin.ignore()
When you call std::cin.ignore() before getline() you are reading (and discarding) the first character waiting to be read in stdin. With the example characters above, after calling std::cin.ignore(), and extracting and discarding the character, the following is left in stdin:
bcd
So now when you do call getline (std::cin, *st); "bcd" are the only characters that are available. That is the reason why you miss the first character.
While you can std::cin.ignore() one character, the .ignore() member function is usually used to read/discard all remaining characters in a line using the form
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Where #include <limits> provides the constants representing the maximum number of the type specified, above <std::streamsize>::max() (e.g. the maximum value that size_t can represent). A large constant is used to ensure the remainder of the line, no matter how long, is consumed and discarded leaving std::cin either empty or with the first character of the next line (in a multi-line buffer) waiting to be read.
std::basic_istream::ignore can also read up to a delimiter character reading/discarding less than the whole line. That can be useful when reading separated fields, or in cases where you use a delimiter with getline() to read less than an entire line.
You either perform your read operation first and then call ignore() to discard unwanted characters to the end of the line, or you can call ignore() first with either a specified number of characters (default 1) or a delimiter to discard the beginning portion of a line up to the first character you want to began your read with.
As you have used it above, it will simply chop off the first character of whatever the user enters -- which does not seem to be what you want. In fact, ignore() isn't even needed above. Remove it and see if the missing character problem doesn't go away.
|
71,920,498 | 71,920,514 | how to get vector from another class in c++ | I am trying to pass a vector plan from a class Administrator, to a class User to use the vector in the report method void report() of this last class, but it seems that the vector arrives empty.
I will shorten the code to leave you a structure that can be better understood
file Administrador.h
class Administrador : public User
{
public:
vector<string> VectorAsign();
};
file Administrador.cpp
vector<string> Administrador::VectorAsign()
{
vector<string> plan = {"one", "two"};
return plan;
}
file User.h
class User
{
public:
vector<string> plan;
void Report(vector<string> plan);
};
file User.cpp
void User::Report(vector<string> plan)
{
this->plan= plan;
for (int i = 0; i < plan.size(); i++)
{
cout << "Date of User::Report" << plan[i] << endl;
}
}
file main.cpp
int main(){
vector<string> plan;
Administrador Admin;
Admin.VectorAsign();
User user;
user.Report(plan);
return 0
}
I've tried a lot, but I can't, is there a better way to pass this vector to another class? thank you
| VectorAsign returns a vector but you are not storing it into a variable.
int main(){
Administrador Admin;
vector<string> plan = Admin.VectorAsign();
User user;
user.Report(plan);
return 0
}
|
71,921,206 | 71,921,710 | How to use double pointers in array | I am in a problem in which I have to write a function which will tokenize the array of characters and then return the array.... I cannnot understand how to use double pointers... The whole code is here:
#include<iostream>
using namespace std;
char** StringTokenize(char*);
int main()
{
char *string1=new char[50];
cout<<"Enter: ";
cin.getline(string1,50);
StringTokenize(&string1[0]);
return 0;
}
char** StringTokenize(char *string1)
{
int i = 0, j = 0;
char **tokenArray[50];
**tokenArray[0] = &string1[0];
while (string1[i] != '\0')
{
tokenArray[i] = string1[i];
i++;
if (string1[i] == ' ')
{
tokenArray[i] = '\n';
i++;
}
else
{
continue;
}
}
tokenArray[i] = '\0';
cout << tokenArray << endl;
return tokenArray;
}
Please help me and write this function for me... Remember that prototype of function should not change
|
and then return the array.
In C++, return type of a function cannot be an array.
char *string1=new char[50];
It's a bad idea to use bare owning pointers to dynamic memory. If the program compiled at all, you would be leaking memory. I recommend using std::string instead.
StringTokenize(&string1[0]);
&string1[0] is redundant. You indirect through a pointer, and then get the address of the result... which is the pointer that you indirected through.
int i = 0, j = 0;
You've declared j, but aren't using it for anything.
char **tokenArray[50];
The pointers to substrings should be pointers to char. It's unclear why your array contains pointers to pointers to char.
Note that these pointers are uninitiallised at the moment.
**tokenArray[0] = &string1[0];
**tokenArray[0] will indirect through the first uninitialised pointer and the behaviour of the program will be undefined. And the right hand side has the aforementioned redundancy.
And the types don't match. The type of left hand operand is char while the type of right hand operand is char*. This is ill-formed and meaningless. Your compiler should be telling you about bugs like this.
tokenArray[i] = string1[i];
tokenArray[i] = '\n';
tokenArray[i] = '\0';
The types don't match. The type of left hand operand is char** while the type of right hand operand is char. These are ill-formed and meaningless. Your compiler should be telling you about bugs like this.
return tokenArray;
This is wrong because
The types don't match. You're supposed to return a char**, but tokenArray is an array of char**.
Returning an automatic array would result in implicit conversion to pointer to first element (which is a char***) and the automatic array would be automatically destroyed after the function returns, so the returned pointer would be invalid.
prototype of function should not change
That's rather unfortunate since it prevents writing a well designed function. You will either have to use static storage for the array, or return an owning bare pointer to (first element of) dynamic array. Neither is a good idea.
|
71,921,483 | 71,922,473 | remove element by position in a vector<string> in c++ | I have been trying to remove the value False and 0;0 from a vector<string> plan; containing the following
1003;2021-03-09;False;0;0;1678721F
1005;2021-03-05;False;0;0;1592221D
1005;2021-03-06;False;0;0;1592221D
1003;2021-03-07;False;0;0;1592221D
1003;2021-03-08;False;0;0;1592221D
1004;2021-03-09;False;0;0;1592221D
1004;2021-03-10;False;0;0;1592221D
1001;2021-03-11;False;0;0;1592221D
but the solutions I have found only work with int, and I tried the following
remove(plan.begin(), plan.end(), "False");
also with erase, but it didn't work
what is the mistake that I am making, or how should I do to eliminate the values that I want, which are in the position [2] [3] and [4], thanks for any help.
| [Note: With the assumption 1003;2021-03-09;False;0;0;1678721F corresponding to a row inside std::vector<string>]
std::remove : Removes from the vector either a single element (position) or a range of elements ([first, last)).
In case std::vector<string> plan contains value False then it is removed.
std::vector < std::string > plan =
{
"1003","2021-03-09","False","0;0","1678721F"
};
std::remove(plan.begin(),plan.end(),"False");
In your case you need to remove given sub-string from each row of the plan. You need to iterate through all the rows to remove given value using std::string::erase.
std::vector < std::string > plan =
{
"1003;2021-03-09;False;0;0;1678721F",
"1005;2021-03-05;False;0;0;1592221D",
"1005;2021-03-06;False;0;0;1592221D",
"1003;2021-03-07;False;0;0;1592221D",
"1003;2021-03-08;False;0;0;1592221D",
"1004;2021-03-09;False;0;0;1592221D",
"1004;2021-03-10;False;0;0;1592221D",
"1001;2021-03-11;False;0;0;1592221D"};
for (auto & e:plan)
{
//As position of False;0;0; is at a fixed index, i.e: from index:16, 10 characters are removed
e.erase (16, 10);
}
To generalize, You can make use of std::String::find to find a sub-string and erase it.
void removeSubstrs(string& s, string p) {
string::size_type n = p.length();
for (string::size_type i = s.find(p);
i != string::npos;
i = s.find(p))
s.erase(i, n);
}
int
main ()
{
std::vector < std::string > plan =
{
"1003;2021-03-09;False;0;0;1678721F",
"1005;2021-03-05;False;0;0;1592221D",
"1005;2021-03-06;False;0;0;1592221D",
"1003;2021-03-07;False;0;0;1592221D",
"1003;2021-03-08;False;0;0;1592221D",
"1004;2021-03-09;False;0;0;1592221D",
"1004;2021-03-10;False;0;0;1592221D",
"1001;2021-03-11;False;0;0;1592221D"};
for (auto & e:plan)
{
removeSubstrs (e, ";False;0;0");
}
for (auto e:plan)
std::cout << e << std::endl;
return 0;
}
|
71,921,709 | 71,924,058 | How to use u8_to_u32_iterator in Boost Spirit X3? | I am using Boost Spirit X3 to create a programming language, but when I try to support Unicode, I get an error!
Here is an example of a simplified version of that program.
#define BOOST_SPIRIT_X3_UNICODE
#include <boost/spirit/home/x3.hpp>
namespace x3 = boost::spirit::x3;
struct sample : x3::symbols<unsigned> {
sample()
{
add("48", 10);
}
};
int main()
{
const std::string s("");
boost::u8_to_u32_iterator<std::string::const_iterator> first{cbegin(s)},
last{cend(s)};
x3::parse(first, last, sample{});
}
Live on wandbox
What should I do?
| As you noticed, internally char_encoding::unicode employs char32_t.
So, first changing the symbols accordingly:
template <typename T>
using symbols = x3::symbols_parser<boost::spirit::char_encoding::unicode, T>;
struct sample : symbols<unsigned> {
sample() { add(U"48", 10); }
};
Now the code fails calling into case_compare:
/home/sehe/custom/boost_1_78_0/boost/spirit/home/x3/string/detail/tst.hpp|74 col 33| error: no match for call to ‘(boost::spirit::x3::case_compare<boost::spirit::char_encoding::unicode>) (reference, char32_t&)’
As you can see it expects a char32_t reference, but u8_to_u32_iterator returns unsigned ints (std::uint32_t).
Just for comparison / sanity check: https://godbolt.org/z/1zozxq96W
Luckily you can instruct the u8_to_u32_iterator to use another co-domain type:
Live On Compiler Explorer
#define BOOST_SPIRIT_X3_UNICODE
#include <boost/spirit/home/x3.hpp>
#include <iomanip>
#include <iostream>
namespace x3 = boost::spirit::x3;
template <typename T>
using symbols = x3::symbols_parser<boost::spirit::char_encoding::unicode, T>;
struct sample : symbols<unsigned> {
sample() { add(U"48", 10)(U"", 11); }
};
int main() {
auto test = [](auto const& s) {
boost::u8_to_u32_iterator<decltype(cbegin(s)), char32_t> first{
cbegin(s)},
last{cend(s)};
unsigned parsed_value;
if (x3::parse(first, last, sample{}, parsed_value)) {
std::cout << s << " -> " << parsed_value << "\n";
} else {
std::cout << s << " FAIL\n";
}
};
for (std::string s : {"", "48", ""})
test(s);
}
Prints
-> 11
48 -> 10
FAIL
|
71,921,797 | 71,921,982 | C++ Concepts: Checking if derived from a templated class with unknown template parameter | Is there a way to use C++ concepts to require that a class is derived from a templated class, whose template parameter is again a derived class from another templated class.
Example:
template <class T>
class A{};
template <class T>
class B{};
class X{};
class Y : public A<X> {};
class Z : public B<Y> {};
How can I check in B, that T is of the form std::is_base_of<A<X>,T> for some X without specifying what X is?
I don't want to add X to the template paramter list of B, because I don't want to change code at every instance where B is derived from (e.g. the last line with class Z).
| If you want to check for specialisations of A specifically, that isn't too difficult.
template <class C>
concept A_ = requires(C c) {
// IILE, that only binds to A<...> specialisations
// Including classes derived from them
[]<typename X>(A<X>&){}(c);
};
The lambda is basically just a shorthand for a function that is overloaded to accept A specialisations. Classes derived from such specialisations also count towards it. We invoke the lambda with an argument of the type we are checking... and the constraint is either true or false depending on whether the call is valid (the argument is accepted).
Then, just plug it in:
template <A_ T>
class B{};
Here it is working live.
|
71,921,980 | 71,958,345 | FFmpeg/libav Storing AVPacket data in a file and decoding them again in a different stream - How to prepare and send custom packets in the decoder? | I want to be able to open a stream with a video file and send in the decoder my own packets with data that I previously stored from a different stream with the same codec. So like forging my own packets in the decoder.
My approach is that I encode frames into packets using H.265 and store the data in a file like this:
AVPacket *packet;
std::vector<uint8_t> data;
...encoding...
data->insert(data->end(), &packet->data[0], &packet->data[packet->size]);
...storing the buffer in a file...
I also have one mkv video with H.265 stream of the same parameters. Now I want to get the stored packet data in the file, create a new packet, and send it into the decoding process of the mkv file. To make it easier I just copy the parameters of the first packet in the mkv stream into a new packet where I insert my data and send it to the decoder. Is this a right approach?
...open decoder with mkv file...
auto packet = av_packet_alloc();
av_read_frame(formatContext, packet);
//here is the packet I will use later with my data
av_packet_copy_props(decodingPacket, packet);
decodingPacket->flags = 0;
//sending the packet from the mkv
avcodec_send_packet(codecContext, packet);
//the data contains the previously stored data
av_packet_from_data(decodingPacket, data.data(), data.size());
avcodec_send_packet(codecContext, decodingPacket);
...retrieving the frame...
However, I am getting this error when I try to send the forget packet:
Assertion buf_size >= 0 failed at libavcodec/bytestream.h:141
I have tried to manually change the decodingPacket->buf->size but that is probably not the problem. I believe that I need to set up some other parameters in the forged packet but what exactly? Maybe I can also somehow store not only the packet data but the whole structure? Please let me know, if there is a better way to store and reload a packet and force it into an unrelated decoder with the same parameters.
Thanks!
EDIT: Seems like the buf_size problem was related to my data which were wrongly retrieved. I can confirm that this works now but I am getting a new error:
[hevc @ 0x559b931606c0] Invalid NAL unit size (0 > 414).
[hevc @ 0x559b931606c0] Error splitting the input into NAL units.
| So the process I've described above seems to be correct and possible! My problem was with the inconsistency of the packets. The encoder and decoder need to be exactly the same (certain codec parameters can apparently produce different kind of packets). The easiest way to achieve that is to create a minimal reference file that would be used to initialize the decoder.
The problem with NAL can be caused by different stream formats of h.265. This great answer helped me with identifying that! The output format affects the packet data so, for example, when having the raw data and using Annex B, it's necessary to insert the start code like:
data.insert(data.begin(), {0,0,0,1});
|
71,922,063 | 71,922,368 | How to add hovered event for QPushButton in Qt Creator? | I'm creating a project in Qt Creator.
I wanna add hovered event for a QPushButton which is created in design mode.
But when I'm clicking go to slot option (which shows available events) i can't see something like hovered().
that's what I can see
When I was searching stackoverflow for this problem I found this (source):
QPushButton#pushButton:hover {
background-color: rgb(224, 255, 0);
}
And my question:
How to implement this on Qt Creator (when the QPushButton is created in design mode)?
Thanks in advance, have a great day :)
| you should use event filter:
look at this example, I add one push button in mainwindow.ui and add eventFilter virtual function.
Don't forget that you should installEventFilter in your pushButton
in mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui
{
class MainWindow;
}
QT_END_NAMESPACE
class MainWindow: public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
// QObject interface
public:
bool eventFilter(QObject *watched, QEvent *event);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
and in mainwindow.cpp :
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QEvent>
MainWindow::MainWindow(QWidget *parent):
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->pushButton->installEventFilter(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if ((watched == ui->pushButton) && (event->type() == QEvent::HoverEnter))
{
qDebug() << "Button is hovered !";
}
return false;
}
the result is :
|
71,922,321 | 71,922,633 | Taking the address of a boost::any variable | Consider:
#include <boost/any.hpp>
#include <iostream>
#include <vector>
#include <string>
int main() {
//Code snippet 1
boost::any variable(std::string("Hello "));
std::string* string_ptr_any = boost::any_cast<std::string>(&variable);
std::cout << "Pointer value is " << string_ptr_any <<", variable's address is " << &variable << std::endl;
//End Code snippet 1
//Code snippet 2
std::string normalstring = "hello_normal";
std::string* normalstringptr = &normalstring;
std::cout << "Pointer value is " << normalstringptr << ", variable's address is " << &normalstring << std::endl;
//End Code snippet 2
//Code snippet 3
std::string& reference_of_string = boost::any_cast<std::string&>(variable);
reference_of_string += "World!";
std::cout << reference_of_string << std::endl;
std::cout << boost::any_cast<std::string>(variable) << std::endl;
//End Code snippet 3
getchar();
}
Running this on compiler explorer gives as output:
Pointer value is 0xc2feb8, variable's address is 0x7ffec1620d68
Pointer value is 0x7ffec1620d40, variable's address is 0x7ffec1620d40
Hello World!
Hello World!
(Q1) As expected, Code snippet 2 gives the same value for both the address of the variable as well as the pointer (0x7ffec1620d40 in this case). But what explains the similar code in Code snippet 1 giving rise to two different addresses? (0xc2feb8 vs 0x7ffec1620d68) What is the relationship between these two addresses in memory?
(Q2) I am unable to see a consistent syntax rule to cast a boost::any variable. In Code snippet 1, to obtain a pointer, the syntax is:
std::string* string_ptr_any = boost::any_cast<std::string>(&variable);
while in Code snippet 3, to obtain a reference, the syntax is:
std::string& reference_of_string = boost::any_cast<std::string&>(variable);
More specifically, why is not the syntax in Code snippet 1:
std::string* string_ptr_any = boost::any_cast<std::string*>(&variable);
Is there a general rule of which these syntaxes are consistent special cases?
|
But what explains the similar code in Code snippet 1 giving rise to two different addresses? (0xc2feb8 vs 0x7ffec1620d68) What is the relationship between these two addresses in memory?
string_ptr_any is the address of the std::string object. &variable is the address of the boost::any object.
why is not the syntax in Code snippet 1:
std::string* string_ptr_any = boost::any_cast<std::string*>(&variable);
Because the boost::any doesn't contain an object of type std::string*. You can only cast to the type that is contained, or a reference to it. This would be an alternative way to write snippet 1:
std::string* string_ptr_any = &boost::any_cast<std::string&>(variable);
|
71,922,594 | 71,922,715 | Import type-alias from class in source | How do I import the type alias of a class for general use in my source file?
I.e., consider I have a file myClass.h with
template<typenmae T>
class myClass {
using vec = std::vector<double>;
vec some_vec_var;
public:
// some constructor and other functions
myClass(T var);
vec some_function(vec some_var);
void some_other_fcn(vec some_var);
};
I've always written my sourcefile (myclass.cpp) in the following manner
#include "myClass.h"
template<typename T>
myClass<T>::myClass(T var){/* */} // fine
template<typename T>
void myclass<T>::some_function(vec some_var){/* */} // fine
// Error: vec was not declared in this scope ...
template<typename T>
vec myClass<T>::some_function(vec some_var){/* */} // not fine
How do I overcome this? Type aliases tend to become tediously long, so simply replacing vec as return-type with its declared alias is not a feasable solution for me.
Do I need to wrap it around a namespace scope? something like
namespace MyNameSpace{
class myClass { ... };
}
as described here: C++: Namespaces -- How to use in header and source files correctly? ?
Or can I just import the namespace of the class somehow?
| Trailing return type (C++11) might help:
template<typename T>
auto myClass<T>::some_function(vec some_var) -> vec
{/* */}
Else you have to fully qualify:
template<typename T>
typename myClass<T>::vec myClass<T>::some_function(vec some_var)
{/* */}
|
71,922,664 | 71,922,924 | C++ Recursive Lambda Memory Usage | I got a Wrong Answer at AtCoder, using Recursive Lambda dfs returning void, like this.
int dfs = y_combinator(
[&](auto self, int cu, int pa = -1) -> int {
dp[cu][0] = dp[cu][1] = 1;
for(auto to: g[cu]){
if(to != pa){
self(to, cu);
dp[cu][0] *= (dp[to][0] + dp[to][1]);
dp[cu][1] *= dp[to][0];
}
}
// return 0;
}
)(0);
Using too much memory (or another point?) seemed to be the reason of WA.
https://atcoder.jp/contests/dp/submissions/31097803
But if I added return value, it resolved.
https://atcoder.jp/contests/dp/submissions/31099529
What happened in this code?
| You have specified a trailing return type for your lambda in both cases. Not returning an int makes your program ill-formed. Heed the compiler:
warning: no return statement in function returning non-void [-Wreturn-type]
As well as that, adding y_combinator_result and y_combinator to namespace std is ill-formed (and pointless, as you have using namespace std'd them back into the global namespace)
|
71,922,917 | 71,926,029 | Is there an efficient way to use random number deduplication? | I making a program that uses random numbers.
I wrote the code as below, but the number of loops was higher than I expected
Is there an efficient way to use random number deduplication?
#include <iostream>
#include <cstdlib>
#include <ctime>
#define MAX 1000
int main(void)
{
int c[MAX] = {};
int i, j = 0;
srand((unsigned int)time(NULL));
for (i = 0; i < MAX; i++)
{
c[i] = rand() % 10000;
for (j = 0; j < i; j++)
{
if (c[i] == c[j])
{
i--;
break;
}
}
}
for (i = 0; i < MAX; i++)
{
std::cout << c[i] << std::endl;
}
return 0;
}
| What you are describing is sampling without replacement. std::sample does exactly that, you just need to supply it with your population of numbers.
std::ranges::views::iota can be your population without having to store 10000 numbers.
#include <algorithm>
#include <random>
#include <ranges>
#include <iostream>
int main()
{
std::vector<int> c(1000);
std::mt19937 gen(std::random_device{}()); // or a better initialisation
auto numbers = std::ranges::views::iota(0, 9999);
std::sample(numbers.begin(), numbers.end(), c.begin(), 1000, gen);
for (int i : c)
{
std::cout << i << std::endl;
}
}
See it live
|
71,923,024 | 71,933,952 | Undefined reference errors in Qt Creator | OpenCV | I linked OpenCV to Qt Creator with the help of this guide. However while compiling a simple code to read and display the image, I am getting undefined reference errors.
test.pro
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
TARGET = opencvtest
TEMPLATE = app
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
INCLUDEPATH += D:\opencv\build\include
LIBS += D:\opencv-build\bin\libopencv_core320.dll
LIBS += D:\opencv-build\bin\libopencv_highgui320.dll
LIBS += D:\opencv-build\bin\libopencv_imgcodecs320.dll
LIBS += D:\opencv-build\bin\libopencv_imgproc320.dll
LIBS += D:\opencv-build\bin\libopencv_features2d320.dll
LIBS += D:\opencv-build\bin\libopencv_calib3d320.dll
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
cv::Mat image = cv::imread("img101.jpg", 1);
cv::namedWindow("My Image");
cv::imshow("My Image", image);
}
MainWindow::~MainWindow()
{
delete ui;
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
These are the errors I am getting while building the file.
Using Windows 10, MinGW 7.3.0 32-bit C and C++ compiler.
| Everything is working now. Apparently I had to link the libraries by right-clicking on the project folder on the left-sidebar, selecting Add Libraries and choosing the External Libraries option (added one by one).
win32: LIBS += -LD:/opencv-build/install/x86/mingw/lib/ -llibopencv_core320.dll
win32: LIBS += -LD:/opencv-build/install/x86/mingw/lib/ -llibopencv_highgui320.dll
win32: LIBS += -LD:/opencv-build/install/x86/mingw/lib/ -llibopencv_imgcodecs320.dll
INCLUDEPATH += D:/opencv-build/install/include
DEPENDPATH += D:/opencv-build/install/include
////NOTE: imgcodecs library is required for imread to work//////
References:
imread OpenCV docs
imgcodecs and imread post
|
71,923,230 | 71,923,319 | Why is my static array not cleared by memset? | I want to have a simple float to string converter for an embedded project and would like to not use floating-point snprintf as that would really fill my flash, so i wrote a simple conversion function. I don't really care for an exact number of decimals nor negative values. This is just a C++ example, i do not want to use STL nor other C++ specific functions as i'm really constrained in terms of space in the real project.
#include <iostream>
#include <cstdio>
#include <cstring>
char msg[100];
typedef uint32_t u32;
char* floatToString(float value)
{
static char placeholder[100];
memset(placeholder, '\0', sizeof placeholder);
auto root = (u32) value;
auto decimals = (u32) (value * 1000) % 1000;
snprintf(placeholder, 100, "%lu.%lu", root,
decimals);
return placeholder;
}
float weirdVal = 11.35;
int main(){
snprintf(msg, 100, "%s,%s", floatToString(weirdVal), floatToString(64.876));
std::cout << msg << '\n';
return 0;
}
When i test the function and call it, i always get the number passed first. My output is:
11.350,11.350
| You are using a common buffer for the converted value.
And since the order of evaluation on your system apparently evaluates the rightmost argument first, you only see the last conversion of 11.35.
You can work around by:
printing the converted values separately
use another kind of buffering (dynamic, local to caller, ...)
Note: You need to format "%lu.%03lu" to get correct results for example for 23.007.
|
71,923,244 | 71,923,520 | What is the fastest way to fill the entire boolean array with a single value (true)? | Which method fills the static boolean array faster?
fill() and fill_n() (defined in the header <algorithm>)
memset() (defined in the headers <cstring> or <string.h>)
loop
What method is recommended for use in C++?
| Except for the for-loop, they all result in the exact same assembler code if you're using a modern C++ compiler and optimizations enabled, take a look at this link: https://godbolt.org/z/1a4a4bKfW
|
71,923,744 | 71,923,891 | How do you swap integers between two files? | I want to copy integers from file A to file B and then from B to A in c++. There is integers 1 2 3 4 5 in file A and B is empty. After running the program file B consists of integers 1 2 3 4 5 while file A is empty somehow. I tried using .clear() and .seekg(0) but it was useless. What have I done wrong?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream A1;
ofstream B1;
ifstream B2;
ofstream A2;
A1.open("C:\\Users\\User\\Desktop\\A.txt");
B1.open("C:\\Users\\User\\Desktop\\B.txt");
int ch;
while (A1 >> ch)
{
B1 << ch << " ";
}
A2.open("C:\\Users\\User\\Desktop\\A.txt");
B2.open("C:\\Users\\User\\Desktop\\B.txt");
/*B1.clear();
B2.clear(); ///didn't work
B2.seekg(0);*/
while (B2 >> ch)
{
A2 << ch << " ";
}
}
| Maybe try calling close() on the streams in between to ensure the pending output is written out before the new streams are opened:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream A1;
ofstream B1;
A1.open("C:\\Users\\User\\Desktop\\A.txt");
B1.open("C:\\Users\\User\\Desktop\\B.txt");
int ch;
while (A1 >> ch)
{
B1 << ch << " ";
}
A1.close();
B1.close();
ifstream B2;
ofstream A2;
A2.open("C:\\Users\\User\\Desktop\\A.txt");
B2.open("C:\\Users\\User\\Desktop\\B.txt");
while (B2 >> ch)
{
A2 << ch << " ";
}
A2.close();
B2.close();
}
|
71,924,499 | 71,924,537 | Why assigning reference to non copyable object is not allowed? | I have a question about C++ references, I'm wondering why the following code is invalid:
class NonCopyable {
public:
NonCopyable() = default;
NonCopyable(const NonCopyable &) = delete;
NonCopyable &operator=(const NonCopyable &) = delete;
};
class RefOwner {
public:
RefOwner(NonCopyable &ref) : ref_(ref) {}
void assign(NonCopyable &ref) { ref_ = ref; } // <- error: use of deleted function ‘NonCopyable& NonCopyable::operator=(const NonCopyable&)’
protected:
NonCopyable &ref_;
};
I was expecting that only the reference to the object (so an address) should be copied, not the whole object, so it should be valid.
The same code using a pointer works just fine:
class RefOwner {
public:
RefOwner(NonCopyable &ref) : ref_(&ref) {}
void assign(NonCopyable &ref) { ref_ = &ref; } // ok
protected:
NonCopyable *ref_;
};
I expected these 2 examples to have the same behaviour, but the first one is invalid. Why is that ?
Thanks for your answers.
|
I was expecting that only the reference to the object (so an address) should be copied, not the whole object, so it should be valid.
That's not how references work. To assign a reference is to assign the referred object.
I expected these 2 examples to have the same behaviour,
References and pointers are fundamentally different. You should not expect them to behave the same.
but the first one is invalid. Why is that ?
Because you are copy assigning a non-copyable object.
|
71,924,684 | 71,925,770 | Is there an std view for random access iterators, as std::span is for contiguous iterators? | Is there a standard view for random access iterators, as std::span is for contiguous iterators?
It is a piece of cake to implement such thing, but I ask before reinvent the wheel. I don't see something like that on cppreference.
| std::span is a pointer and a size (or equivalently two pointers). It doesn't need to do type erasure.
A random_access_view would have the overhead of type erasure, so I don't expect one to be standardised.
Instead I would suggest a template constrained to std::ranges::random_access_range, possibly in conjunction with std::ranges::viewable_range if you need a view specifically.
|
71,924,937 | 71,927,972 | gmock template class 'const T1': actual parameter with requested alignment of 64 won't be aligned | I am trying to gmock the following template class
template <typename Type>
class Interface {
public:
virtual bool insert(const Type& param);
}
by using gmock as follows
template <typename Type>
class CMockInterface: public Interface<Type> {
MOCK_METHOD1_T(insert, bool(const Type&));
}
when building I get the following errors
error C2718: 'const T1': actual parameter with requested alignment of 64 won't be aligned
note: see reference to class template instantiation 'testing::internal::ImplicitlyConvertible<const T &,testing::internal::BiggestInt>' being compiled
what is this error?
| This is a known bug in GoogleTest, and was fixed a while ago. Try updating GoogleTest to at least 1.10.0.
|
71,925,006 | 71,926,398 | Regarding arithemetic operations with std::numeric_limits<T>::infinity() | I have a peculiar usecase where I have some edges w/ double weights set initially to std::numeric_limits<double>::infinity(). These weights will be set to something else later on in program execution.
Now that we have the context, here is the main issue. I need to compare these edge weights to the square of some weight that I compute, and to account for the squaring of my computed weight, I will also have to square the edge weights. Of course, this will result in an initial multiplying of infinity by infinity. I am wondering if multiplying a double set to std::numeric_limits<double>::infinity() by itself is defined behavior. Can I expect it to remain unchanged?
I could not find any documentation even on cppreference.
| Restricting this answer to IEEE754, using +/-Inf as some sort of starting value brings a fair bit of trouble.
Under IEEE754,
Inf * 0.0 = NaN
-Inf * 0.0 = Inf * -0.0 = -NaN
Inf * Inf = -Inf * -Inf = Inf
-Inf * Inf = -Inf
Inf multiplied by any positive floating point value (including a subnormal value) is Inf, and similarly for -Inf.
In other words, you need to treat +0.0 and -0.0 as special cases when multiplying, and is one of those rare cases where a signed negative zero produces a different result. Use std::isnan to test, if you cannot adopt some other scheme.
|
71,925,020 | 71,925,239 | Provide constexpr-safe simplified exception message when consteval'd, otherwise stringstream verbose info | Imagine this simple constexpr function:
// Whatever, the exact values don't matter for this example
constexpr float items[100] = { 1.23f, 4.56f };
constexpr int length = 12;
constexpr float getItem(int index)
{
if (index < 0 || index >= length)
{
// ArrayIndexOutOfRangeException has a constructor that takes a const char* and one that takes a std::string.
throw ArrayIndexOutOfRangeException("You did a bad.");
}
return items[index];
}
You can use it like this:
int main()
{
constexpr float f1 = getItem( 0); std::cout << f1 << std::endl; // Works fine
constexpr float f2 = getItem( 1); std::cout << f2 << std::endl; // Works fine
constexpr float f3 = getItem(-1); std::cout << f3 << std::endl; // Does not compile: "constexpr variable 'f3' must be initialized by a constant expression", "subexpression not valid in a constant expression"
constexpr float f4 = getItem(20); std::cout << f4 << std::endl; // Does not compile: "constexpr variable 'f4' must be initialized by a constant expression", "subexpression not valid in a constant expression"
return 0;
}
Great! BUTT WEIGHT!
volatile int i;
i = 123; // As a placeholder for something like this: std::cin >> i;
float f5 = getItem(i);
std::cout << f5 << std::endl;
This throws at runtime with "terminate called after throwing an instance of 'ArrayIndexOutOfRangeException'" and "what(): You did a bad."
Ok, that's not very helpful and I want to create a better error message:
constexpr float getItem(int index)
{
if (index < 0 || index >= length)
{
std::stringstream stream;
stream << "You did a bad. getItem was called with an invalid index (" << index << "), but it should have been non-negative and less than the total number of items (" << length << ").";
throw ArrayIndexOutOfRangeException(stream.str());
}
return items[index];
}
But that's not allowed: "variable of non-literal type 'std::stringstream' (aka 'basic_stringstream') cannot be defined in a constexpr function".
I'd be OK with having a simpler error message for the compile-time version and only do the complicated string manipulation in the run-time version.
So... How?
Please note that this is C++17 (some GCC flavor), which might not have some constexpr-related features that C++20 would have.
Other code requires that the function stays constexpr.
I would like to avoid duplicating the function, if at all possible.
| You might move the error message creation in another function:
std::string get_error_message(int index, int length = 10)
{
std::stringstream stream;
stream << "You did a bad. getItem was called with an invalid index ("
<< index
<< "), but it should have been non-negative "
<< "and less than the total number of items ("
<< length << ").";
return stream.str();
}
constexpr float getItem(int index)
{
constexpr int length = 10;
constexpr std::array<float, length> items{};
if (index < 0 || index >= length)
{
throw std::runtime_error(get_error_message(index, length));
}
return items[index];
}
Demo
|
71,925,038 | 74,361,765 | Spheroid line_interpolate - but in the other direction | Using boost::geometry::line_interpolate with boost::geometry::srs::spheroid, I'm calculating great circle navigation points along the shortest distance between 2 geographic points. The code below calculates the navigation points for the shortest distance around the great circle. In some rare cases, I need to generate the longer distance that wraps around the globe in the wrong direction. For example, when interpolating between a lon/lat of (20, 20) to (30, 20), there only 10 degrees of difference in the shorter direction and 350 degrees in the other. In some cases I would like the ability to want to interpolate in the longer direction (e.g. 350 deg).
This 2d map shows shows the 10 degree longitude difference in red, and 350 degrees green. I drew the green line by hand to the line is only an approximation. How can I get the points for this green line?
This code is based on the example from boost.org, line_interpolate_4_with_strategy
#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
int main()
{
typedef boost::geometry::model::d2::point_xy<double, boost::geometry::cs::geographic<boost::geometry::degree> > Point_Type;
using Segment_Type = boost::geometry::model::segment<Point_Type>;
using Multipoint_Type = boost::geometry::model::multi_point<Point_Type>;
boost::geometry::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);
boost::geometry::strategy::line_interpolate::geographic<boost::geometry::strategy::vincenty> str(spheroid);
Segment_Type const start_end_points { {20, 20}, {30, 20} }; // lon/lat, interpolate between these two points
double distance { 50000 }; // plot a point ever 50km
Multipoint_Type mp;
boost::geometry::line_interpolate(start_end_points, distance, mp, str);
std::cout << "on segment : " << wkt(mp) << "\n";
return 0;
}
| Note that line_interpolate interpolates points on a linestring where a segment between two points follows a geodesic.
Therefore, one workaround could be to create an antipodal point to the centroid of the original segment and create a linestring that follows the requested path. Then call line_interpolate with this linestring. The following code could do the trick.
#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
int main()
{
namespace bg = boost::geometry;
using Point_Type = bg::model::d2::point_xy<double, bg::cs::geographic<bg::degree>>;
using Segment_Type = boost::geometry::model::segment<Point_Type>;
using Linstring_Type = bg::model::linestring<Point_Type>;
using Multipoint_Type = bg::model::multi_point<Point_Type>;
bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);
bg::strategy::line_interpolate::geographic<bg::strategy::vincenty> str(spheroid);
Segment_Type const start_end_points { {20, 20}, {30, 20} };
Point_Type centroid;
bg::centroid(start_end_points, centroid);
Point_Type antipodal_centroid;
bg::set<0>(antipodal_centroid, bg::get<0>(centroid) + 180);
bg::set<1>(antipodal_centroid, bg::get<1>(centroid) * -1);
Linstring_Type line;
line.push_back(start_end_points.first);
line.push_back(antipodal_centroid);
line.push_back(start_end_points.second);
double distance { 50000 }; // plot a point ever 50km
Multipoint_Type mp;
bg::line_interpolate(line, distance, mp, str);
std::cout << "on segment : " << wkt(mp) << "\n";
return 0;
}
The result looks like this:
Note that since the spheroid you are constructing is non-spherical then there is no great circle (apart from equator and meridians) and the geodesic segment is not closed but looks like this. Therefore you will notice that the last interpolated point will be different from the segment's endpoint.
|
71,925,091 | 71,925,211 | Differentiating between functions with same name from different header files | I'm currently writing a 2D vector class which contains a function to round x and y of the vector to the nearest int. to do this I thought I could use the <math.h> round() but the name of my Vector2 function is Vector2.round(), this causes an error because the computer thinks I'm giving too many arguments (1) because my Vector2.round() function isn't meant to take any arguments, I though putting math::round() instead of round() might work but I guess the math library doesn't use a namespace because it didn't work, how can I tell the computer that I'm trying to access the <math.h> method as opposed to the one I wrote.
| There Are Two Approaches:
Using ::round() instead of math::round(). This Approach is however compiler dependent and as cited here works well only for Microsoft Or GNU Compiler.
Using cmath library. Supports the same functions as math.h but its functions are present in std namespace allowing you to use std::round() as cited here
|
71,925,242 | 71,964,704 | Open a pop up window with a push button QTcreator | i'm actually working on a project. Then, i want to open a pop up window with some other informations when i click on a push button which is on my main window. I work in c++ with QTcreator but i don't really know how to do that, and i didn't found on web a topic which could help me.
I have started to create an other class for my pop up's containt, and i've written the next method to open it but it doesn't work.
void MainWindow::button_is_pushed()
{
pop_up_create_analyse* create_device_widget = new pop_up_create_analyse(this);
create_device_widget->show();
}
| Try declaring pop_up_create_analyse* outside of the method.
On your actual code, your pointer will be deleted immediately.
Didn't know what kind of widget is it, but you may also try changing the "show()" to "exec()". Exec() will actually wait for the window to be closed.
|
71,925,555 | 71,926,605 | using file lock for a single instance program fails if spawn child process | I need to have a single instance program in Linux. That is if someone tries to run the program the new instance should print a message and exit. At the moment I have a lock mechanism like this:
main() {
// init some stuff...
// set or check lock
auto pidFile = open("/var/run/my-app.lock", O_CREAT | O_RDWR, 0666);
auto rc = flock(pidFile, LOCK_EX | LOCK_NB);
if(rc) {
if(errno == EWOULDBLOCK) {
cout << "Program is already running!\n";
exit(0);
}
}
// do other stuff or the main loop
// when the loop ends by sigkill or sigterm or ...
exit(0);
}
The problem is if I do anything that spawns child processes using int system(const char *command); and at some point, someone uses "kill" to end this program, the child processes will stay alive and the lock will not get deleted hence preventing my app to run again.
Is there a solution to this shortcoming?
| You need O_CLOEXEC as a flag to open(). Then the handle won't be open in the child process.
system() eventually calls exec(), which is how new process binaries are loaded.
|
71,925,755 | 71,925,905 | Concatenate Bits from 3 characters, taken from different locations in the bitset | I am trying to concatenate the bits of 3 characters a, b and c into a bitset of 16 bits. The constraints are the following:
Concatenate the last 2 bits of a into newVal1
Concatenate the 8 bits of b into newVal1
Concatenate the first 2 bits of c into newVal1
On paper I am getting: 1111111111110000 same as the result. But I am not sure of the way I am concatenating the bits. First shift left by 14 character a then shift left by 6 character b and finally, since There is no space left for character c then shift right by 2. Is there a better way to do it? It's already confusing for me
#include <iostream>
#include <bitset>
int main() {
int a = 0b11111111 & 0b00000011;
int b = 0b11111111;
int c = 0b11111111 & 0b11000000;
uint16_t newVal1 = (a << 14) + (b << 6) + (c >> 2 );
std::cout << std::bitset<16>(newVal1).to_string() << std::endl;
return 0;
}
| First of all you need to consider the signed and unsigned integer problem. With signed integers you can get unexpected sign extensions, adding all ones at the top. And possible overflow will lead to undefined behavior.
So the first thing I would do is to use all unsigned integer values.
Then to make it clear and simple, my suggestion is that you do all the shifting on newVal1 instead, and just do bitwise OR into it:
unsigned a = /* value of a */;
unsigned b = /* value of b */;
unsigned c = /* value of c */
unsigned newVal1 = 0;
newVal1 |= a & 0x02; // Get lowest two bits of a
newVal1 <<= 8; // Make space for the next eight bits
newVal1 |= b & 0xffu; // "Concatenate" eight bits from b
newVal1 <<= 2; // Make space for the next two bits
newVal1 |= (c >> 6) & 0x02; // Get the two "top" bits from c
Now the lowest twelve bits of newVal1 should follow the three rules set up for your assignment. The bits top bits will be all zero.
|
71,926,225 | 71,926,432 | In-scope QTimer runs on Ubuntu but not on Windows | I'm facing a problem with QTimer on Windows.
The context of usage is the following :
I read a file, line by line, and trigger a 10s timer before starting
If the file is processed in less than 10s, then everything is fine
If the file is too big, then i don't want to spend too much CPU reading it and stops after 10 sec even thought I did not reach the end
Here is the code :
//Function readModel, with arguments path and modelType
//Check if files exists and opens it
QTimer readPointsTimer;
readPointsTimer.setInterval(10000);
readPointsTimer.setSingleShot(true);
readPointsTimer.start();
in.seek(0); //The file is already opened if it exists
while (!in.atEnd() && m_process){ //While I did not reach the end of the file, or the user didn't ask to stop
qDebug() << "remaining" << readPointsTimer.remainingTime();
if(readPointsTimer.remainingTime()==0 && m_readPoints){
m_process = false;
m_fileReadEntirely = false;
readCommentsTimer.start();
}
//Read line
QString line = in.readLine();
//Some process function not important for this post
}
readPointsTimer.stop();
//Some finalization not important for this post
The problem I have is the following : In Ubuntu this code runs fine. The timer is triggered and the qDebug() displays a countdown. When it reaches 0 the while loop stops as expected. On windows the story is different. The qDebug() always displays "10000", as is the timer had started but was not counting down.
To give more context, this function is triggered to run in a concurrent thread :
void ModelManager::loadModel(ModelManager::MODEL_TYPE type, const QString &path)
{
m_loadingFuture = QtConcurrent::run(this,&ModelManager::readModel, type, path);
}
Do you know what could cause this behavior on Windows ? Is the function badly coded even for Ubuntu or is this some Windows peculiarity ?
Thank you in advance
| Without having tested that hypothesis, I assume that it could be a problem that writing to the screen typically takes quite some time; to improve this, it is typically buffered; meaning that when you execute qDebug() << "remaining" << readPointsTimer.remainingTime();, you don't actually directly write to the screen, but instead to some internal buffer, which is then flushed occasionally (but doing that takes some time). But all that while it's still filling the buffer again; you write to qDebug each loop cycle, so each line of the file, meaning you could write it millions of times...
To prevent overwhelming the output buffer (and in general to avoid unnecessary excess output), I would write the output less often, say every second or so:
QElapsedTimer t;
t.start();
while (!in.atEnd() && m_process){ //While I did not reach the end of the file, or the user didn't ask to stop
if (t.elapsed() > 1000)
{
qDebug() << "remaining" << readPointsTimer.remainingTime();
t.start();
}
// ...
}
And while you're at that, you could even completely replace the QTimer with the simpler QElapsedTimer.
You actually don't seem to need a QTimer - its main functionality is to start some function periodically, or when "finished". All the currently shown code uses the QTimer for is to measure the time that has passed since starting to read the file (by querying the remainingTime()).
|
71,926,511 | 71,926,907 | How to store all subclasses in different sets c++ | I want to store objects relative to their type.
I have a Status class which is inherited to create different status such as Burn, Stun, etc...
I would like to store statuses in sets with a set for each type (a character can a multiple burn status at once, so I want to get the set storing all the burn statuses but not other statuses).
my solutions so far looks like this
std::map<std::type_index, std::set<Status*>> statuses;
// access all Burn statuses
for (const Burn* b : statuses.find(typeid(Burn))->second) {} // error : E0144 a value of type "Status *" cannot be used to initialize an entity of type "const DamageModifier *"
**
However this is downcasting and the compiler doesn't want it to work.
My questions are as follow:
How could I access a set and downcast it to the right type without copying
Do you think of any other way to store all statuses of the same subtype together with easy access ?
I dont want to store it all in a set and dynamic cast because it starts getting expensive
I dont want to declare one set by hand for each new Status subclass.
Edit :
The problem was that I tried to do two things at once from my last code version
Switching from std::set<Status*> to std::map<std::typeid, std::set<Status*>> which is OK as long as you cast the result the same as before
Trying to implicitly cast a whole set of pointer which is useless and naive, at least in this context
Both answer helped me realise the problem was that I tried to do both at once.
|
How could I access a set and downcast it to the right type without copying
You can use static_cast to down cast:
for (const Status* s : statuses.find(typeid(Burn))->second) {
auto b = static_cast<const Burn*>(s);
}
You must be very careful though to not insert pointers to wrong derived classes into wrong set. That will silently pass compilation and break at runtime (if you're lucky).
|
71,926,671 | 71,926,805 | Trying to print out object contents using a class method. Keep getting "error: statement cannot resolve address of overloaded function" | beginner here, I am working on an assignment for a course and while working on this program, I am experiencing some troubles. I cannot figure out how to print out the contents within an object I have in my main method using a different method from a class I made.
Here's my code:
#include <iostream>
using namespace std;
class Book {
private:
string title;
int pages;
double price;
public:
Book () {
title = "";
pages = 0;
price = 0.0;
}
Book(string t, int p, double pr) {
title = t;
pages = p;
price = pr;
}
void setPrice(double);
void getBookInfo(Book, Book);
};
void Book::setPrice(double pr) {
price = pr;
}
void Book::getBookInfo(Book b1, Book b2) {
cout << b1.title << b1.pages << b1.price << endl;
cout << b2.title << b2.pages << b2.price << endl;
}
int main() {
Book b1("C++ Programming", 802, 90.55);
Book b2("Chemistry Tests", 303, 61.23);
b2.setPrice(77.22);
b1.getBookInfo;
b2.getBookInfo;
return 0;
}
I need to print out the contents of Book b1 and Book b2 using the getBookInfo() method, but every time I think I know what I'm doing, I get "error: statement cannot resolve address of overloaded function" on b1.getBookInfo and b2.getBookInfo.
Of course, I will format it on my own so the output isn't all bunched together, but I can't even get it to output anything!
This is my first time working with class and constructors, so I am really kinda lost right now. Help is appreciated! Thank you!
| The error is coming from here:
b1.getBookInfo;
b2.getBookInfo;
you are trying to call methods of a class but didn't use the call operator () so you are instead loading the address of the method. To solve this error use the call operator to call the methods:
b1.getBookInfo(b1, b2);
b2.getBookInfo(b1, b2);
beside that your code has many faults but you indicated you are a beginner so this isn't unusual
|
71,927,290 | 71,927,518 | recommended way to floor time_point to a given duration | I have a user-provided duration
const int period_seconds = cfg.period_seconds;
I would like to floor a time_point to the granularity of that duration.
I see that there is a std::chrono::floor function for time_point and duration, but it's not immediately obvious how to use them to do what I'm looking for.
I have the following toy example which works:
const auto seconds = std::chrono::seconds{period_seconds};
const auto period = std::chrono::duration_cast<std::chrono::nanoseconds>(seconds);
const auto now = std::chrono::system_clock::now();
const auto floored = now - (now.time_since_epoch() % period);
The net effect of the above code, for a duration of 10 seconds would be the following:
now: 2022-04-19 15:06:26.781772408
floored: 2022-04-19 15:06:20.000000000 # so "floors" the 25.78 seconds to 20 seconds
I can't help but feel that working in terms of the time_since_epoch and a modulus operator isn't the "right" way of getting the result I'm looking for...
Is there a "better" / recommended way to floor a time_point to some user-provided duration?
| Your solution looks pretty good to me. However it can be slightly simplified. There's no need to form the nanoseconds-precision period. You can operate directly with seconds:
const auto floored = now - (now.time_since_epoch() % seconds);
|
71,927,593 | 71,933,630 | rapidjson Schema Document multiple roots error | I am using RapidJSON to parse JSON files. I am trying to use a rapidjson::SchemaDocument to make a JSON schema to validate received JSON files.
But, when I try to construct a schema document that was generated by website liquid-technologies.com, "error code 2" is received, which indicates that the JSON (schema) document I am trying to parse has multiple roots, even though it has only one.
Here is the schema document I am trying to parse:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"title": {
"type": "string"
},
"pay": {
"type": "number"
},
"country": {
"type": "string"
},
"employer": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"workforce": {
"type": "integer"
},
"officelocation": {
"type": "string"
}
},
"required": [
"name",
"workforce",
"officelocation"
]
},
"location": {
"type": "string"
},
"flexibleHours": {
"type": "boolean"
},
"description": {
"type": "string"
}
},
"required": [
"title",
"pay",
"country",
"employer",
"location",
"flexibleHours",
"description"
]
}
And here is my code:
std::string schemaJson = readFile("../jsonschemas/postjobschema.json");
rapidjson::Document sd;
if (sd.Parse(schemaJson.c_str()).HasParseError()) {
std::cout << "Schema has parse errors" << std::endl;
if (sd.GetParseError() == rapidjson::kParseErrorDocumentRootNotSingular)
std::cout << "There are multiple roots" << std::endl;
}
Is my schema incorrect, or am I doing something wrong?
| I think you schema is correct, but there is something wrong with your code.
I have tested your scehma json and a mock input json with rapidjson's example/schemavalidator, it turns out everything works well.
input.json:
{
"title": "foo",
"pay": 100,
"country": "US",
"employer": { "name": "bar", "workforce": 12, "officelocation": "UK"},
"location": "CA",
"flexibleHours": true,
"description": "hello"
}
./bin/schemavalidator /tmp/schema.json < /tmp/input.json
Input JSON is valid.
Would you like to read your schema json file with rapidjson::FileReadStream?
// Read a JSON schema from file into Document
Document d;
char buffer[4096];
{
FILE *fp = fopen(argv[1], "r");
if (!fp) {
printf("Schema file '%s' not found\n", argv[1]);
return -1;
}
FileReadStream fs(fp, buffer, sizeof(buffer));
d.ParseStream(fs);
if (d.HasParseError()) {
fprintf(stderr, "Schema file '%s' is not a valid JSON\n", argv[1]);
fprintf(stderr, "Error(offset %u): %s\n",
static_cast<unsigned>(d.GetErrorOffset()),
GetParseError_En(d.GetParseError()));
fclose(fp);
return EXIT_FAILURE;
}
fclose(fp);
}
|
71,927,693 | 71,928,101 | Can I use a std::string variable as an argument to an operator? | For example, if I have:
#include <iostream>
using namespace std;
int main()
{
int b = 1;
int c = 2;
string a = "(b + c)";
cout << (4 * a) << "\n";
return 0;
}
Is it possible to have string a interpreted literally as if the code had said cout << (4 * (b + c)) << "\n";?
| No. C++ is not (designed to be) an interpreted language.
Although it's theoretically possible to override operators for different types, it's very non-recommended to override operators that don't involve your own types. Defining an operator overload for std::string from the standard library may break in future. It's just a bad idea.
But, let's say you used a custom type. You could write a program that interprets the text string as a arithmetic expression. The core of such program would be a parser. It would be certainly possible, but the standard library doesn't provide such parser for you.
Furthermore, such parser wouldn't be able to make connection between the "b" in the text, and the variable b. At the point when the program is running, it has no knowledge of variable names that had been used to compile the program. You would have to specify such information using some form of data structure.
P.S. You forgot to include the header that defines std::string.
|
71,927,760 | 71,927,831 | error: use of deleted function ‘pQueue::pQueue(const pQueue&)’ note: <func> is implicitly deleted because the default definition would be ill-formed | I'm new to c++ and am encountering this error while building the code. Found some answers online but am unable to understand them. Can someone please explain what this error means and how to resolve it in simple terms?
For reference, I'm attaching the code snippets. These snippets are part of a project, so might miss out on a few details.
file.cpp
#include "File.h"
using namespace std;
pQueue::pQueue()
{
std::priority_queue<std::pair<int, Category*>> q;
}
pQueue::~pQueue()
{
}
void queueWork(std::priority_queue<std::pair<int, Category*>> q, int action, Category* data)
{
q.emplace(make_pair(action, data));
}
void doWork(std::priority_queue<std::pair<int, Category*>> q)
{
while (true)
{
std::pair<int, Category*> queueElement;
queueElement = q.top();
Category* data = queueElement.second;
// Perform some operation, get return value
q.pop();
}
}
file.h
#pragma once
#include <queue>
#include <thread>
class pQueue
{
public:
pQueue();
~pQueue();
void queueWork(std::priority_queue<std::pair<int, Category*>> q, int action, Category* data);
private:
void doWork(std::priority_queue<std::pair<int, Category*>> q);
};
main.cpp
#include "File.h"
bool function(Category* data)
{
if (data)
{
// Will set action values later
auto action = 1;
pQueue::queueWork(Queue, action, data);
// TODO: Implement getResult function to get the return value
}
return true;
}
| I would use the rule of zero here (see rule of 3 and rule of 5)
class pQueue {
public:
void queueWor(int action, Category* data);
private:
void doWork();
std::priority_queue<std::pair<int, Category*>> q;
};
The compiler generated destructor, copy, and move will be correct and sufficient in this case.
Note that in your current implementation q is not a member variable, instead it is simply a local variable that only exists within the scope of your constructor.
|
71,928,000 | 71,944,203 | Error MSB8020 The build tools for Visual Studio 2010 (Platform Toolset = 'v100') cannot be found, but v100 not used | I get the following error when I try to build my Visual Studio C++ project:
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.Cpp.Platform.targets(55,5): error MSB8020: The build tools for Visual Studio 2010 (Platform Toolset = 'v100') cannot be found. To build using the v100 build tools, please install Visual Studio 2010 build tools. Alternatively, you may upgrade to the current Visual Studio tools by selecting the Project menu or right-click the solution, and then selecting "Retarget solution". [C:\path\to\src\li.vcxproj]
However, I only have v140 in my project:
$ grep -hrIi platformtoolset .
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
<PlatformToolset>v140</PlatformToolset>
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit:WindowsTargetPlatformVersion=8.1
#TargetFrameworkVersion=v4.0:PlatformToolSet=v140_xp:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native64Bit:WindowsTargetPlatformVersion=
I tried retargeting the solution as suggested in the error message, but I didn't see any option for v140 in the dropdown:
I cannot upgrade to v141, because my team's CI builds run on Visual Studio 2015, and I believe Visual Studio 2015 does not have v141.
Why could I be getting this error, and how can I fix it?
| It turns out the problem was that I only made the settings changes for one of the projects in the solution, and I failed to make the settings changes to the entire solution. The platform toolset error message was just a red herring.
|
71,928,827 | 71,929,065 | What does the integer shown in typeid().name() mean? | What does the integer shown in the output of typeid().name() mean? For example:
#include<iostream>
#include<typeinfo>
class implementer{
public :
void forNameSake()
{
}
};
int main()
{
implementer imp2;
std::cout<<typeid(imp2).name();
}
Gives the output:
11implementer
What does the 11 in the output mean?
|
What does the 11 in the output mean?
In this particular case, most probably it means the length of the identifier that follows. implementer is 11 characters.
You might be interested in https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.name, specifically in the <source-name> ::= <positive length number> <identifier> part.
|
71,928,845 | 71,931,330 | Get the location of all contours present in image using opencv, but skipping text | I want to retrieve all contours of the image below, but ignore text.
Image:
When I try to find the contours of the current image I get the following:
I have no idea how to go about this as I am new to using OpenCV and image processing. I want to get ignore the text, how can I achieve this? If ignoring is not possible but making a single bounding box surrounding the text is, than that would be good too.
Edit:
Criteria that I need to match:
The contours may very in size and shape.
The colors from the image may differ.
The colors and size of the text inside the image may differ.
| Here is one way to do that in Python/OpenCV.
Read the input
Convert to grayscale
Get Canny edges
Apply morphology close to ensure they are closed
Get all contour hierarchy
Filter contours to keep only those above threshold in perimeter
Draw contours on input
Draw each contour on a black background
Save results
Input:
import numpy as np
import cv2
# read input
img = cv2.imread('short_title.png')
# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# get canny edges
edges = cv2.Canny(gray, 1, 50)
# apply morphology close to ensure they are closed
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
# get contours
contours = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
contours = contours[0] if len(contours) == 2 else contours[1]
# filter contours to keep only large ones
result = img.copy()
i = 1
for c in contours:
perimeter = cv2.arcLength(c, True)
if perimeter > 500:
cv2.drawContours(result, c, -1, (0,0,255), 1)
contour_img = np.zeros_like(img, dtype=np.uint8)
cv2.drawContours(contour_img, c, -1, (0,0,255), 1)
cv2.imwrite("short_title_contour_{0}.jpg".format(i),contour_img)
i = i + 1
# save results
cv2.imwrite("short_title_gray.jpg", gray)
cv2.imwrite("short_title_edges.jpg", edges)
cv2.imwrite("short_title_contours.jpg", result)
# show images
cv2.imshow("gray", gray)
cv2.imshow("edges", edges)
cv2.imshow("result", result)
cv2.waitKey(0)
Grayscale:
Edges:
All contours on input:
Contour 1:
Contour 2:
Contour 3:
Contour 4:
|
71,929,094 | 71,929,145 | Range Based For Loop on std::array | I have an array of arrays and want to fill them up with some value.
This doesn't work:
std::array<std::array<int, 5>, 4> list;
for (auto item : list) {
std::fill(item.begin(), item.end(), 65);
}
However, this does:
for (int i = 0; i < 4; i++) {
std::fill(list[i].begin(), list[i].end(), 65);
}
What am I missing? Looking at the debugger, the first example does nothing on list. The type of item is std::array<int, 5>, as expected, so I'm not sure what went wrong.
| In your first code snippet, the item variable will be a copy of each array in the loop; so, modifying that will not affect the 'originals'. In fact, as that item is never actually used, the whole loop may be "optimized away" by the compiler.
To fix this, make item a reference to the iterated array elements:
for (auto& item : list) {
//...
|
71,929,111 | 71,929,209 | Is there any difference between initializing a class instance with a constructor versus an assignment? | Is there any difference between declaring and initializing a class instance like this:
MyClass var(param1, param2);
...and this?
MyClass var = MyClass(param1, param2);
I vaguely recall hearing that they're equivalent at some point, but now I'm wondering if the latter case might also call the class's assignment operator, move constructor, or copy constructor rather than just the specific constructor that's explicitly used.
| The latter is not an assignment. It's syntax called copy initialisation:
type_name variable_name = other;
The former is direct initialisation:
type_name variable_name(arg-list, ...);
Prior to C++17, there was technically creation of temporary object from the direct initialisation MyClass(param1, param2), and call to copy (or move since C++11) constructor in the latter case. There was no practical difference1 as long as that copy/move was well-formed because that copy was allowed to be optimised away. But it would have been ill-formed if the class wasn't copyable nor movable.
Since C++17, there is no difference1 even for the abstract machine. There's no temporary object and no copy that would need to be optimised. param1, param2 are passed directly to the constructor that initialises var just like what happened previously due to optimisation.
1 Except for the case where the constructor is explicit, in which case copy-initialisation syntax is not allowed as demonstrated by Daniel Langr.
|
71,929,274 | 71,929,302 | Function not declared in scope even after declaring it before int main in C++ | I have created two vectors, x_listand y_list. I have two functions declared before int main named x_i and y_j, which are used to extract element one before the value is called. Eg If x_i(2) is called x_list[1] would be the answer same for y_j. I have read a few answers about this problem, saying that variables should be inside the scope, but I could find that problem in my code.
#include<iostream>
#include<iomanip>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
void display(vector<double> &v){
for (int i = 0; i < v.size(); i++)
{
cout<<v[i]<<" ";
}
cout<<endl;
}
//-------------------------------
double x_i(int node_number)
{
x_list[node_number-1];
}
//------------------------------
double y_j(int node_number)
{
y_list[node_number-1];
}
//-----------------------------
int main(){
const int N = 401;
const double pi = 3.141592653589793;
double L = pi/2;
double r = 1.5;
//-------------------------------------------------------------------
vector<double> x_list_0_to_pidiv2;
double val;
for (int i = 0; i < (int(N/4)+1); i++)
{
val = ((L/2)*((1-(tanh(r*(1-(2*((i*(1))/int(N/4)))))/(tanh(r))))));
x_list_0_to_pidiv2.push_back(val);
}
//---------------------------------------------------------------------
vector<double> dx_list;
double diff;
for (int i = 0; i < (((x_list_0_to_pidiv2).size())-1); i++)
{
diff = x_list_0_to_pidiv2[i+1]-x_list_0_to_pidiv2[i];
dx_list.push_back(diff);
}
//----------------------------------------------------------------------
// reversing the dx_list
reverse(dx_list.begin(), dx_list.end());
//----------------------------------------------------------------------
vector<double> x_list;
double entry1,entry2;
for (int i = 0; i < ((x_list_0_to_pidiv2).size()); i++)
{
entry1 = x_list_0_to_pidiv2[i];
x_list.push_back(entry1);
}
for (int k = 0; k < (dx_list.size()); k++)// equi to line 28 py
{
entry2 = x_list[k+(dx_list.size())] + dx_list[k];
x_list.push_back(entry2);
}
//----------------------------------------------------------------------
vector<double> dx_final_list;
double diff2,val2;
for (int i = 0; i < (x_list.size()-1); i++)
{
diff2 = x_list[i+1] - x_list[i];
dx_final_list.push_back(diff2);
}
for (int i = 0; i <(dx_final_list.size()); i++)
{
val2 = x_list[i+dx_final_list.size()] + dx_final_list[i];
x_list.push_back(val2);
}
//----------------------------------------------------------------------
vector<double> y_list;
double val3;
for (int i = 0; i < x_list.size(); i++)
{
val3 = x_list[i];
y_list.push_back(val3);
}
The error is as follows:
trialc++.cpp: In function 'double x_i(int)':
trialc++.cpp:20:5: error: 'x_list' was not declared in this scope
x_list[node_number-1];
^~~~~~
trialc++.cpp: In function 'double y_j(int)':
trialc++.cpp:25:5: error: 'y_list' was not declared in this scope
y_list[node_number-1];
^~~~~~
Note: List is written just for namesake, the datatype is vector everywhere
Any help is highly appreciated!!
| x_list and y_list are local variables inside of main(), so they are out of scope of the code in x_i() and y_j(). You would have to pass in the variables as extra parameters to those functions, just like you do with display(), eg:
double x_i(const vector<double> &x_list, int node_number)
{
return x_list[node_number-1];
}
double y_j(const vector<double> &y_list, int node_number)
{
return y_list[node_number-1];
}
...
int main(){
...
vector<double> x_list;
vector<double> y_list;
double d;
...
d = x_i(x_list, some_node_number);
...
d = y_j(y_list, some_node_number);
...
}
|
71,929,671 | 71,931,335 | variables defined in linker script not coming through in c++ startup file | I have the following linker script (left out irrelevant parts)
MEMORY
{
PROGRAM_FLASH (rx) : ORIGIN = 0x60000000, LENGTH = 0x40000
SRAM_DTC (rwx) : ORIGIN = 0x20000000, LENGTH = 0x10000
SRAM_ITC (rwx) : ORIGIN = 0x0, LENGTH = 0x10000
SRAM_OC (rwx) : ORIGIN = 0x20200000, LENGTH = 0x20000
}
ENTRY(ResetISR)
SECTIONS
{
/* Image Vector Table and Boot Data for booting from external flash */
.boot_hdr : ALIGN(4)
{
FILL(0xff)
__boot_hdr_start__ = ABSOLUTE(.) ;
KEEP(*(.boot_hdr.conf))
. = 0x1000 ;
KEEP(*(.boot_hdr.ivt))
. = 0x1020 ;
KEEP(*(.boot_hdr.boot_data))
. = 0x1030 ;
KEEP(*(.boot_hdr.dcd_data))
__boot_hdr_end__ = ABSOLUTE(.) ;
. = 0x2000 ;
} >PROGRAM_FLASH
.vector : ALIGN(4)
{
FILL(0xff)
__vector_table_flash_start__ = . ;
__vector_table_dtc_start__ = LOADADDR(.vector) ;
KEEP(*(.isr_vector))
. = ALIGN(4) ;
__vector_table_size__ = . ;
} >PROGRAM_FLASH
So relevant takeaways:
flash memory starts at 0x600000000
some XIP boot bytes are written to dedicated locations beginning of flash, followed by "my own stuff".
I put vector tables at 0x60002000 (or better put, nxp sdk expects some xip bytes and jumps to 0x60002000 where I can put my own stuff).
I am creating some variables with the current location so that I can use them in my startup script
When I look at the disassembled code, i can clearly see that my vector tables described 0x45 words, so with above linker script I would expect that my __vector_table_size__ at least would be 0x45
In my startup .cpp I added some externs so that I can read the memory info created by the linker.
extern unsigned int __vector_table_flash_start__;
extern unsigned int __vector_table_dtc_start__;
extern unsigned int __vector_table_size__;
/* some temp vars so that my assignments don't get optimized out */
volatile unsigned int i;
volatile unsigned int ii;
volatile unsigned int iii;
__attribute__ ((naked, section(".after_vectors.reset")))
void ResetISR(void) {
// Disable interrupts
__asm volatile ("cpsid i");
__asm volatile ("MSR MSP, %0" : : "r" (&_vStackTop) : );
//__asm volatile ("LDR r9, = __global_offset_table_flash_start__");
i = __vector_table_flash_start__;
ii = __vector_table_dtc_start__;
iii = __vector_table_size__;
}
Again, nothing interesting, just some code to make sure nothing is optimized out, and that I can see the actual values of the variables in the debugger.
When we know that my flash starts at 0x60000000 and that my .vector section has an offset of 0x2000
Variable
Expected
Actual
vector_table_flash_start
0x6002000
0x20010000
vector_table_dtc_start
0x6002000
0x20010000
vector_table_size
0x45
0xffffffff
What I am doing wrong here??
For reference, the relevant section of disassemble (arm-none-eabi-objdump --disassemble-all eclipse/MIMXRT1024_Project/Debug/MIMXRT1024_Project.axf > disassemble_pic)
| You need to check the address of the linker script variables, not their value. The address is what the linker script sets. The value is what happens to be at that address - presumably the first vector in the vector table.
|
71,930,078 | 71,930,786 | C++ syntax, is this a lambda | I'm building a test automation solution for a test process. I ran into a link, but my C++ competency isn't that great. Could someone please explain the syntax below?
void read_loop(bp::async_pipe& p, mutable_buffer buf) {
p.async_read_some(buf, [&p,buf](std::error_code ec, size_t n) {
std::cout << "Received " << n << " bytes (" << ec.message() << "): '";
std::cout.write(boost::asio::buffer_cast<char const*>(buf), n) << "'" << std::endl;
if (!ec) read_loop(p, buf);
});
}
How to retrieve program output as soon as it printed?
My solution needs to orchestrate binaries, that monitor data traffic. There are two main programs. One manages other programs, call it B. Program A just stores all data. The testing process should inspect the outputs and match some keywords. If matched, test passes. The high level solution should do I/O to all programs--manipulating states, and matching 'outputs'.
| What a lambda looks like:
// This is the basics of a lambda expression.
[ /* Optional Capture Variables */ ]( /*Optional Parameters */ ) {
/* Optional Code */
}
So the simplest lambda is:
[](){}
What are the different parts:
Capture Variables: Variables from the current visible scope
that can be used by the lambda.
Parameters: Just like a normal function, these are parameters
that are passed to the parameter when it is invoked.
Code: This is the code that is executed and uses the
above mentioned variables when the lambda is invoked.
I think it is useful to consider what is likely (not specified) going on behind the senes. A Lamda is just syntactic sugar for a functor (a callabale object).
int main()
{
int data = 12;
// define the lambda.
auto lambda = [&data](int val){
std::cout << "Lambda: " << (val + data) << "\n";
};
lambda(2); // activate the lambda.
}
This is semantically equivalent to the following:
class CompilerGeneratedClassNameLambda
{
int& data;
public:
CompilerGeneratedClassNameLambda(int& data)
: data(data)
{}
void operator()(int val) const {
std::cout << "Lambda: " << (val + data) << "\n";
}
};
int main()
{
int data = 12;
CompilerGeneratedClassNameLambda lambda(data);
lambda(2); // activate the lambda.
}
In your code. This part is the lambda:
[&p,buf](std::error_code ec, size_t n) {
std::cout << "Received " << n << " bytes (" << ec.message() << "): '";
std::cout.write(boost::asio::buffer_cast<char const*>(buf), n) << "'" << std::endl;
if (!ec) read_loop(p, buf);
}
|
71,930,082 | 71,930,165 | std::map - decrement iterator gives strange result? | Can't seem to work this out. Simple example as follows:
#include <iostream>
#include <map>
int main() {
std::map<uint32_t, char> m;
m[1] = 'b';
m[3] = 'd';
m[5] = 'f';
std::map<uint32_t, char>::iterator i = m.lower_bound('d');
std::cout << "First: " << i->first << std::endl;
// Decrement the iterator
i--;
// Expect to get 1, but get 5?
std::cout << "Second: " << i->first << std::endl;
return 0;
}
The output is:
First: 3
Second: 5
Why do I get 5 here? I thought decrementing the iterator would result in it pointing at key 1
| This call
std::map<uint32_t, char>::iterator i = m.lower_bound('d');
returns the iterator m.end(). So dereferencing the iterator
std::cout << "First: " << i->first << std::endl;
results in undefined behavior.
The member function lower_bound expects an argument that specifies a key not value.
Consider the following demonstration program.
#include <iostream>
#include <iomanip>
#include <map>
#include <cstdint>
int main()
{
std::map<uint32_t, char> m;
m[1] = 'b';
m[3] = 'd';
m[5] = 'f';
std::map<uint32_t, char>::iterator i = m.lower_bound( 'd' );
std::cout << "i == m.end() is " << std::boolalpha << ( i == m.end() ) << '\n';
}
The program output is
i == m.end() is true
Instead you could write for example
std::map<uint32_t, char>::iterator i = m.lower_bound( 5 );
After decrementing the iterator after this call
std::map<uint32_t, char>::iterator i = m.lower_bound('d');
it points to the last element of the map.
|
71,930,448 | 71,930,500 | Declaring a char pointer | I'm trying to make a login/register project and I have difficulties in declaring the char* tempUsername from this code (SIGSEVG segmentation fault)
char *tempUsername, *tempPassword, *tempPasswordConfirm, *tempSecurityQuestion;
/*
no other declaration for tempUsername here
*/
std::cout<<"Enter your new username:\n";
std::cin>>tempUsername;
//process stops here
if(fileSearch(newFilename(tempUsername))) {
std::cout<<"Username already exists! Choose another username!\n";
}
else {
std::cout<<"Enter your password:\n";
std::cin>>tempPassword;
std::cout<<"Confirm your password:\n";
I'm having a hard time understanding anything about pointers, so any advice is more than helpful!
|
char *tempUsername
std::cin>>tempUsername;
The problem here is that your pointer is uninitialised. When you try to extract from the input stream into the uninitialised pointer, the behaviour of the program will be undefined. Don't do this.
Your goal seems to be to read a string of user input. A solution that I can recommend is to use the std::string class:
std::string tempUsername;
std::cin >> tempUsername;
No need to use a pointer to achieve this.
I can use a char* as an array of chars, is that true?
It is not true in general. If you have a char* that points to an element of an array of char, then you can use that char* as an iterator to access the elements of the array.
|
71,930,510 | 71,930,724 | Where is VS Configuration Properties stored | I'm running a C++ solution filled with a number of projects. I have set each project up so that when running out of the IDE, the Debugging->Working Directory points to $(ProjectDir)..$(Configuration) per my projects requirements. All is well regarding that, but i cannot find where that change exists, therefore i can't check it in.
Does VS store that off in a file that relates to the project/solution file? or is it hidden somewhere else where each developer needs to set it up?
| Those settings are stored alongside your C++ project, in a separate file named <your_project_name>.vcxproj.user (which is an XML-file as well). For the particular setting you mention, look at the LocalDebuggerWorkingDirectory element there.
Typically, you would exclude .user files from version control, to allow developers to maintain their own, independent debugging configuration. But perhaps in your case you could agree on a particular working directory team-wide and push the .user file as well.
EDIT: However, there seems to be a better solution: to utilize the .vcxproj file itself (instead of the .user file) and just store the LocalDebuggerWorkingDirectory element there, by manually editing the project file. See https://stackoverflow.com/a/38300298/1458097
|
71,930,721 | 71,931,319 | how to overload minus operator to subtract two fractional numbers? | I want to subtract two fractional numbers using operator overloading. I have write a piece of code in order to accomplish this task:
#include<iostream>
using namespace std;
void HCF(int& a, int& b)
{
int m, n;
m = a;
n = b;
while (m != n)
{
if (m > n)
m = m - n;
else
n = n - m;
}
a = a / m;
b = b / m;
}
class Rational {
int x1;
int y1;
public:
void simplify()
{
int m, n, r;
n = fabs(y1);
m = fabs(x1);
while (r = m % n)//Find the Maximum Common Number of m,n
{
m = n;
n = r;
}
y1 /= n; // Simplification
x1 /= n;
if (y1 < 0) // Convert denominator to positive number
{
y1 = -y1;
x1 = -x1;
}
}
Rational(int num = 0, int denom = 1)
{
if (denom) {
x1 = num;
y1 = denom;
}
else {
x1 = 0;
y1 = 1;
}
}
Rational(const Rational& copy)//Copy Constructor
{
x1 = copy.x1;
y1 = copy.y1;
}
Rational operator-(const Rational& x) const //Overloaded minus operator
{
Rational temp;
temp.x1 = x1 * x.y1 - x.x1 * y1;
temp.y1 = y1 * x.y1;
temp.simplify();
return temp;
}
operator string() const //Overloaded string operator
{
int numerator = x1, denominator = y1;
HCF(numerator, denominator);
string str;
if (denominator == 1)
str = to_string(numerator);
else
str = to_string(numerator) + "/" + to_string(denominator);
return str;
}
};
int main()
{
Rational a(5, 1);
Rational b(3, 4);
Rational c;
Rational d;
Rational x(5, 1);
c = a - x;
string expected1 = "0"; //Expected value
string actual1 = (string)c;//Actual value
cout << actual1.compare(expected1);//Comparing actual and expected value
d = c - b;
string expected2 = "-3/4";
string actual2 = (string)d;
cout << actual2.compare(expected2);
}
As we can see, in the main() function, both cout statements should print 0 because when we compare both strings, they must be equal. But the problem is, when I run this program, it prints nothing, and I don't know why.
My operator string() converts an integer fraction into a string. My operator- takes the LCM and finds the final value after subtracting two fractional numbers. In the main() function, I have declared five objects for class Rational, and then I simply perform subtraction and then I compare the expected and actual values, which should return 0 in the cout statement.
I have also used the simplify() member function to check whether the fraction is completely in simpler form or not. For example, it should simplify 2/4 into 1/2.
Where is the mistake? All other functions except operator- are running correctly. The real problem is with the operator-, ie when we perform c=a-x, the value of c would be 0 as a string. Similarly, if we perform d=c-b then the expected value should be -3/4 as a string.
I have also tried to run this code on Google Test, but it fails the test case.
| Use this GCD (greatest common divisor) function to implement your HCF function. Yours currently exhibits an endless loop when given 0 as a first argument.
To reduce a fraction, divide numerator and denominator by their greatest common divisor.
This is called the Euclidean algorithm.
template <typename T>
T GCD(T a, T b) {
while (b != 0)
{
T t = a % b;
a = b;
b = t;
}
return std::max(a, -a);
}
|
71,931,068 | 71,931,190 | On Linux QDir::entrylist() not returning all files and directories for /dev | I know the /dev device files aren't regular files but didn't notice anything
in the documentation about that being an issue.
My code simply creates a QDir for /dev and uses the QDir::entrylist() method
to display the list of files and directories. It appears to be only printing
directories under /dev but no device files.
| Dir::system filter causes the QDir::entrylist() to print system files (i.e., sda1 ...) and so on.
|
71,931,854 | 71,932,562 | Practical Schenarios that can (or should) be solved by using C++ std::array instread of other STL or C style array | Despite the multiple questions about performance\benefits\properties of std::array vs std::vector or C style array, I still never got a clear answer about
actual practical usage and types of problems that can be (and should be solved with std::array). the reason i am asking is because me myself and in all the projects that i was working in C++ i never saw any usage of std::array but most of the work done with std::vector, is some are cases we used std:deque.
After compering the properties seems like array is something in the middle that like a C style array that have a thin(not so thin - have a lot of APIs) layer of abstraction but not heavy as std::vector. feel like if performance really matter or i have limitation because of embedded device i would still use C style array.
I tried to compare some other relatively large C++ project for example Notepad++ source code, and they very seldom use std::array only in json.hpp which is third party of its own, so to summarize
What are actual practical usage that can be solved by std::array better then other STL or native array?
is it possible that modern C++ compiler can optimize away all the abstraction leaving it basically like native C array.
I noticed in json.hpp that used by notepad++ source code that std::array used with char_traits and templates, is it possible that std::array can be used in implementation of other Libraries that are using templates and template meta-programming heavily while native C array would require more adapters or workaround that have performance penalty?
EDIT: I understand that std::array properties like fixed size and the sizes is known, but why it is still relatively seldom used.
Thanks a lot :)
| This question is somewhat broad and seems likely to go down the opinionated route, still:
ad.1
std::array provides STL-like API for C-style array. Moreover it prevents the array to pointer decay. The latter is oftentimes desired, e.g. due to the fact that size information is preserved when passing it.
ad.2
As for a general case - yes, std::array is a simple thin wrapper around its C-style counterpart. For specific cases - passing std::array by value can cause copies, which won't be the case for C-style array as the simply cannot be passed by value. On the other hand, this also provides a more consistent interface.
Generally - if you are concerned about performance - measure.
I dare say, in most cases it won't matter at all and if a form of static array is needed, std::array should be a go-to type over the C-style one, see C++ core guidelines on that topic.
Ad.3
Not sure I follow. Again: what std::array is, is mostly a convenience wrapper around C-style one. If you're interested in the gory details, you can look up boost::array, it should be pretty close to the std one.
True, using C-style arrays would probably require more tinkering or just writing sth equivalent to the std::array class template. As for potentially less performant workarounds, the main one I can think of is vector or some other form of dynamically allocated storage.
Note, I wrote "potentially": contemporary compilers are allowed to elide heap operations, so again - measure first, judge later.
Also, the array vs vector dilemma often goes down to fixed-size vs. resizable , i.e. the intent of the programmer. Of course there is a plethora of exceptions to this rule, but for a most general case I'd opt for being expressive first.
|
71,932,085 | 71,932,154 | What's the difference between having a library as a dependency in a makefile vs without the dependency symbol | I'm quite new to makefiles, and I'm wondering what exactly is the role of the library in this format:
app: app.o mylibrary.a
$(LD) -o $@ $(LDFLAGS) app.o mylibrary.a
What I usually see would be something like this:
app: app.o
$(LD) -o app $(LDFLAGS) $^ mylibrary.a
My understanding for this format is that the executable will be made from the app.o file, which has a dependency on mylibrary.a.
I can't quite understand the difference/meaning of the first version though.
| Where the $@ is the target is substituted, in the first case that would be app.
Although they aren't defined in the question, the $(LD) and $(CFLAGS) are usually defined as the c-compiler and the flags to use in the compiler.
E.g. something like CFLAGS = -g -Wall -std=c99 -lstdc++ would be a defined line at the top of the Makefile.
I'd usually write these as the first two parts of the command to run for the target.
The $^ indicates to substitute everything that is listed as a dependency of the target. In the first row the dependencies are app.o mylibrary.a whereas in the second it is only app.o. These ($^, $@)are usually used to simplify the writing of make rules.
The choice of whether to use the wildcards-as these are called-is really your own choice. I usually use them because they make it easier to write and maintain.
So to answer your question the main difference is where you explicitly need to place the name of the file.
Additional note on dependencies
The files in the line where there are dependencies of the target listed are used by make to determine which targets need to be rerun. Make does a topological sort of the dependencies and if something changes-based on last touched time of file-the make command will rerun the target if it is within the path of the make target that is being called.
|
71,932,286 | 71,932,484 | Elements of a class aggregate | I am trying to understand the changes that happened from C++14 to C++17 regarding aggregate initialization. From §9.4.2[dcl.init.aggr]/2:
The elements of an aggregate are:
(2.1) for an array, the array
elements in increasing subscript order, or
(2.2) for a class, the
direct base classes in declaration order, followed by the direct
non-static data members ([class.mem]) that are not members of an
anonymous union, in declaration order.
This paragraph defines what the elements of an aggregate class are. In particular, I can't get what the bold sentence means. I have this example to demonstrate my confusion:
struct Base { int mem1, mem2; };
struct Derived : Base { int mem3, mem4; };
Derived obj = { 1, 2, 3, 4 };
The object obj is an aggregate since it satisfies the criteria defined in [dcl.init.aggr]/1. My problem, however, is what are the elements of this aggregate. It seems that the elements are Base::mem1 initialized with 1, Base::mem2 initialized with 2, Derived::mem3 initialized with 3, and Dervied::mem4 initialized with 4.
But [dcl.init.aggr]/2 states the opposite. It is said that the elements are the data members of the direct base classes, which is Base in this case, followed by the direct non-static data members of the Derived class. Am I parsed the wording correctly?.
I really don't know whether or not I understood the quote correctly, but I think I don't. So any explanation regarding this point will help me alot.
| Your understanding of the concept "elements of an aggregate" is correct. However, that's not the end of aggregate initialization. There is brace elision:
Braces can be elided in an initializer-list as follows. If the initializer-list begins with a left brace, then the succeeding comma-separated list of initializer-clauses initializes the elements of a subaggregate; it is erroneous for there to be more initializer-clauses than elements. If, however, the initializer-list for a subaggregate does not begin with a left brace, then only enough initializer-clauses from the list are taken to initialize the elements of the subaggregate; any remaining initializer-clauses are left to initialize the next element of the aggregate of which the current subaggregate is an element.
All implicit type conversions ([conv]) are considered when initializing the element with an assignment-expression. If the assignment-expression can initialize an element, the element is initialized. Otherwise, if the element is itself a subaggregate, brace elision is assumed and the assignment-expression is considered for the initialization of the first element of the subaggregate.
Since Base b = 1; is not a valid initialization statement, brace elision is assumed, as defined in the first paragraph.
|
71,932,814 | 71,932,940 | C++/ Dynamic Assignment | Create *Std as a global variable.
Create *Std as many Num as you enter.
This code is not executed because Num is contained within main().
Is there a way to set *Std as a global variable while getting Num input from main()?
#include <iostream>
#include <string>
using namespace std;
struct s1 {
string str1;
};
s1* Std = new s1[Num];
int main()
{
cout << "How many [Std] do you want to create? : ";
int Num;
cin >>Num;
for (int i = 0; i < Num; i++)
{
getline(cin, Std[i].str1);
cout << "\nStd["<<i<<"].str1 : " << Std[i].str1<<"\n\n";
}
}
| Variables don't have to be initialized at the time they are declared. You can separate declaration from assignment.
In this case, you can leave Std as a global variable, if you really want to (though, globals are generally frowned upon, and in this case it is unnecessary since there are no other functions wanting to access Std), however you must move the new[] statement into main() after Num has been read in, eg:
#include <iostream>
#include <string>
using namespace std;
struct s1 {
string str1;
};
s1* Std;
int main()
{
cout << "How many [Std] do you want to create? : ";
int Num;
cin >>Num;
Std = new s1[Num];
for (int i = 0; i < Num; i++)
{
getline(cin, Std[i].str1);
cout << "\nStd[" << i << "].str1 : " << Std[i].str1 << "\n\n";
}
delete[] Std;
}
That being said, you should use the standard std::vector container instead whenever you need a dynamic array, eg:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct s1 {
string str1;
};
vector<s1> Std;
int main()
{
cout << "How many [Std] do you want to create? : ";
int Num;
cin >>Num;
Std.resize(Num);
for (int i = 0; i < Num; i++)
{
getline(cin, Std[i].str1);
cout << "\nStd[" << i << "].str1 : " << Std[i].str1 << "\n\n";
}
}
|
71,932,819 | 71,933,027 | C++: Can thread race conditions corrupt static/global integer values on a per-byte level? | Let's say I have two threads that randomly increment or decrement from a static int variable in the global scope. My program is not concerned with the exact value of this variable, only whether it is generally increasing or decreasing over-time.
Though I have written some assembly code during college, I am not familiar with how CPUs deal with multithreading and communicate between cores. Is there any chance that two simultaneous writes can corrupt a global variable on a per-byte level? Or are reads and writes to memory (e.g. move, load, store) always atomic?
I use Visual Studio 2022 and C++17, and am hoping to target all modern desktop CPUs (intel, AMD).
| The CPU is the least of your problems here. C++ states that any of these interactions represents undefined behavior. As such, consider the following code:
int i; //Global variable.
void some_func()
{
i = 5;
if(i > 5)
{
//A
}
}
The compiler can see all of the code between assigning to i and checking its value. It can see that there is no inter-thread synchronization between these two operations. Because the C++ standard states that any modifications to i from another thread under these circumstances yield undefined behavior, the compiler is free to assume that such modifications do not happen.
Therefore, the compiler knows that i will never be greater than 5 at this point and therefore may remove the block "A" and conditional test, not even emitting assembly that could be executed.
That is what "undefined behavior" means.
If you want to play around with things like that, if you want to actually use the behavior of your CPU/cache/etc in such scenarios, you're going to need to operate in a lower-level language. And for what it's worth, the C standard has more-or-less the same wording, so C ain't it.
So long as you are working in C or C++, the question you are asking is fundamentally unanswerable.
|
71,933,185 | 71,956,958 | Loading a DLL with LoadLibraryA(path_to_dll) is changing the inherit handle flag (HANDLE_FLAG_INHERIT) from 1 to 0 for file descriptors 0, 1, and 2 | We have written some functions in golang and a c wrapper on top of that to invoke those functions. We first build golang code to create an archive file and then we build the wrapper code in c to be consumed as a DLL.
After loading this DLL using LoadLibraryA(path_to_dll) in my program I am seeing that the inherit flags for fd 0, 1, and 2 are getting changed from 1 to 0. This does not happen immediately after loading the DLL though. I had added sleep in my code after the load library call and seems like it takes a few milliseconds after loading the library to change the flag values.
I am using GetHandleInformation((HANDLE) sock, &flags) to get the inherit flag value.
Any idea/pointers on what could be causing this? Thanks!
Updates:
I was able to find out the exact line in the go code that is flipping the inherit flag values. The global variable reqHandler in below k8sService.go code is causing this. Any idea why the use of this global variable is flipping the inherit flag values?
my-lib/k8sService.go (go code)
package main
import "C"
import (
"my-lib/pkg/cmd"
)
func main() {
}
var reqHandler []*cmd.K8sRequest
my-lib/pkg/cmd/execute.go
import (
"my-lib/pkg/dto"
)
type K8sRequest struct {
K8sDetails dto.K8sDetails
}
my-lib/pkg/dto/structs.go
package dto
// K8sDetails contains all the necessary information about talking to the cluster. Below struct has few more variables.
type K8sDetails struct {
// HostName of the cluster's API server
HostName string `json:"hostname"`
// Port on which the API server listens on to
Port int `json:"port"`
}
We have a C wrapper on top of the above k8sService.go. We first build golang code to create an archive file and then with this archive file and wrapper code in C we build the target DLL. Below is the sample program which loads this DLL and also prints the inherit flag values before and after loading the DLL.
#include <windows.h>
#include <iostream>
#include <io.h>
#include "wrapper/cWrapper.h"
void printInheritVals() {
typedef SOCKET my_socket_t;
my_socket_t fd0 = _get_osfhandle(0);
my_socket_t fd1 = _get_osfhandle(1);
my_socket_t fd2 = _get_osfhandle(2);
std::cout << "fd0: " << fd0 << std::endl;
std::cout << "fd1: " << fd1 << std::endl;
std::cout << "fd2: " << fd2 << std::endl;
DWORD flags;
int inherit_flag_0 = -1;
int inherit_flag_1 = -1;
int inherit_flag_2 = -1;
if (!GetHandleInformation((HANDLE) fd0, &flags)) {
std::cout << "GetHandleInformation failed" << std::endl;
} else {
inherit_flag_0 = (flags & HANDLE_FLAG_INHERIT);
}
if (!GetHandleInformation((HANDLE) fd1, &flags)) {
std::cout << "GetHandleInformation failed" << std::endl;
} else {
inherit_flag_1 = (flags & HANDLE_FLAG_INHERIT);
}
if (!GetHandleInformation((HANDLE) fd2, &flags)) {
std::cout << "GetHandleInformation failed" << std::endl;
} else {
inherit_flag_2 = (flags & HANDLE_FLAG_INHERIT);
}
std::cout << "inherit_flag_0: " << inherit_flag_0 << std::endl;
std::cout << "inherit_flag_1: " << inherit_flag_1 << std::endl;
std::cout << "inherit_flag_2: " << inherit_flag_2 << std::endl;
}
int main()
{
printInheritVals(); // In output all flag values are 1
HINSTANCE hGetProcIDDLL = LoadLibraryA(PATH_TO_DLL);
if (!hGetProcIDDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Library loaded" << std::endl;
printInheritVals(); // In output all flag values are 1
Sleep(1000);
printInheritVals(); // In output all flag values are 0
return EXIT_SUCCESS;
}
| This is a bug in the golang.org/x/sys/windows package. The same issue used to be in the built-in syscall package as well, but it was fixed in Go 1.17.
Something in your project must be importing the golang.org/x version of the package instead of the built-in one, and so the following code executes to initialize the Stdin, Stdout, and Stderr variables:
var (
Stdin = getStdHandle(STD_INPUT_HANDLE)
Stdout = getStdHandle(STD_OUTPUT_HANDLE)
Stderr = getStdHandle(STD_ERROR_HANDLE)
)
func getStdHandle(stdhandle uint32) (fd Handle) {
r, _ := GetStdHandle(stdhandle)
CloseOnExec(r)
return r
}
The fix for that code would be to remove the CloseOnExec call, which is what clears HANDLE_FLAG_INHERIT on the given file handle.
How to solve that in your project is less clear. I think you can vendor golang.org/x/sys module in your project, perhaps with a replace directive in your go.mod. Apply the fix in your local copy.
Meanwhile, I encourage you to also report the bug. The documentation instructs you to report the issue on the main Go project at GitHub, prefixing the title with x/sys.
|
71,933,678 | 71,933,740 | C++ Template specialization matches different functions with namespace op | I have run into a situation that looks like this. I am using g++ on Windows 10.
#include <stdio.h>
template<typename _t>
struct test_thing {};
template<typename _t> void test_2(_t) { printf("A"); }
template<typename _t>
void test()
{
//test_2(_t{}); // prints: ABC
::test_2(_t{}); // prints: ABA <-- namespace op, searching different?
}
template<> void test_2(double) { printf("B"); }
template<typename _t> void test_2(test_thing<_t>) { printf("C"); }
int main()
{
test<int>();
test<double>();
test<test_thing<int>>();
return 0;
}
My question is why/how is the namespace op changing how the compiler is searching for the function to call. Doesn't the compiler find the most specialized template function that matches the args? If test_2(test_thing<_t>) is defined above test it finds it, but only with the ::, not below.
|
Doesn't the compiler find the most specialized template function that matches the args?
Function templates can't be partial specialized. The last test_2 is overloaded with the 1st one.
template<typename _t> void test_2(_t) { printf("A"); } // overload #1
template<typename _t>
void test()
{
//test_2(_t{}); // prints: ABC
::test_2(_t{}); // prints: ABA <-- namespace op, searching different?
}
template<> void test_2(double) { printf("B"); } // explicit specialization for overload#1
template<typename _t> void test_2(test_thing<_t>) { printf("C"); } // overload #2
Given test_2(_t{});, ADL helps and finds the 2nd overloaded test_2. For ::test_2(_t{}); ADL won't take effect, only the 1st test_2 (and its specialization) could be found.
|
71,933,869 | 71,934,908 | Can anybody provide a MISRA C++ compliant 'offsetof' macro/template/function that works with static_assert? | I'm trying to write defensive code and put static_assert<> to ensure a structure's member has a specific offset to satisfy some hardware requirements
MISRA C++ Rule 18-2-1 says "The macro offsetof shall not be used", so we've 'undef'd offsetof.
We've provided some template things, but they all fail when used in static_assert<>
I've been unable to find something that works with C++11 static_assert<> across compilers.
struct Commands
{
uint32_t command[4];
};
struct DMA_Bundle
{
struct header_
{
uint32_t num_of_elems;
uint8_t reserved[60];
} header;
Commands array[16];
};
I'm trying to assure that array is 64 bytes from the beginning.
static_assert(offsetof(DMA_Bundle,array)==64,"zoinks");
Does works, but MISRA says but I can't use that. (and I can't argue with our functional safety people :/)
I've tried the following, and generally they don't work:
static_assert(offsetofarray()==64,"bar");
static_assert(myoffsetof(DMA_Bundle::array)==64,"double_zoinks");
The explicit offsetofarray() constexpr function does work under GCC 7.5.0, but it fails under later GCC and Clang (which is what our embedded processor tools use). It fails with 'non constant condition for static_assert'.
The other seems to complain of "invalid use of non-static data member 'DMA_Bundle::array'"
And, for what it's worth, I'm limited to C++11.
| Some background:
And, for what it's worth, I'm limited to C++11
And here is your first problem...
MISRA C++:2008 only allows the use of C++:2003 - anything after this is out of scope.
MISRA C++ Rule 18-2-1 says "The macro offsetof shall not be used", so we've 'undef'd offsetof.
Use of #undef is a violation of required Rule 16-0-3 (and it is unnecessary to #undef offsetof)
Now to address the main point:
Rule 18-2-1 is a required Rule which seeks to protect against undefined behaviour when the types of the operands are incompatible.
Does works, but MISRA says but I can't use that. (and I can't argue
with our functional safety people :/)
The problem with many clip-board monitors is they can tick boxes, but adopt a "MISRA says no" attitude without understanding what MISRA actually says...
My suggestion, especially if only being used when associated with static_assert() is to raise a deviation (see section 4.3.2 and the extended guidance in MISRA Compliance).
A deviation is a perfectly legitimate approach, where a Rule may be causing an inconvenience, but the undefined behaviour is not applicable.
ETA (noting discussion with Lundin about C): In MISRA C:2004, there was an equivalent guideline (Rule 20.6) which likewise imposed a blanket restriction on offsetof - in MISRA C:2012 this blanket restriction was dropped, with the undefined behaviour captured by the general Rule 1.3
In many respects, this makes justification of a MISRA C++ deviation easier - as the rationale would be matching the MISRA C decision.
See profile for affiliation
|
71,934,248 | 71,934,449 | How to detect if template argument is an std::initializer_list | In the following example, the last line fails because the conversion operator of JSON has to choose between two possibilities:
std::vector<int>::operator=(std::vector<int>&&)
std::vector<int>::operator=(std::initializer_list<int>)
How can I constrain JSON::operator T() so it ignores the initializer_list overload?
struct JSON
{
using StorageType = std::variant<
int,
float,
std::string,
std::vector<int>,
std::vector<float>
>;
StorageType storage;
template<class T>
operator T() const {
return std::get<T>(storage);
}
};
int main(int argc, char* argv[])
{
const JSON json;
std::vector<int> numbers;
numbers = json; // more than one operator '=' matches these operands
return 0;
}
| You can use enable_if to disable the conversion of initializer_list
template<class>
constexpr inline bool is_initializer_list = false;
template<class T>
constexpr inline bool is_initializer_list<std::initializer_list<T>> = true;
struct JSON
{
// ...
template<class T, std::enable_if_t<!is_initializer_list<T>>* = nullptr>
operator T() const {
return std::get<T>(storage);
}
};
Demo
|
71,934,769 | 71,942,109 | How to iterate over boost graph to get incoming and outgoing edges of vertex? | I am trying to iterate over boost graph. While iterating, I am trying to find incoming edges and outgoing edges from that vertex. But I am getting segmentaion fault.
I tried to debug and found the line where it throws segmentation fault.
(vertex -> vertex of the graph of which incoming and outgoing edges needs to find out)
(graph -> boost graph )
//Finding out edges of vertex
boost::graph_traits<BGType>::out_edge_iterator ei, ei_end;
boost::tie(ei, ei_end) = out_edges( vertex, graph ); // error at this line
for( boost::tie(ei, ei_end) = out_edges(vertex, graph); ei != ei_end; ++ei)
{
auto target = boost::target ( *ei, graph );
graph[target]._isVisible = false;
}
//Finding in edges of vertex
boost::graph_traits<BGType>::in_edge_iterator ein, ein_end;
boost::tie(ein, ein_end) = in_edges( vertex, graph ); // error at this line
for( boost::tie(ein, ein_end) = in_edges(vertex, graph); ein != ein_end; ++ein)
{
auto source = boost::source ( *ein, graph );
graph[source]._isVisible = false;
}
| boost::tie(ei, ei_end) = out_edges( vertex, graph ); // error at this line
boost::tie(ein, ein_end) = in_edges( vertex, graph ); // error at this line
Both comments suggest that either graph or vertex are invalid. Check that graph is still a valid reference to an object.
If so, then "obviously" vertex is incorrect. It could be out-of-range. Consider checking it:
void hide_neighbours(BGV vertex, BGType& graph) {
assert(vertex < num_vertices(graph));
And while you're at it, we can simplify the implementation:
void hide_neighbours(BGV vertex, BGType& graph) {
assert(vertex < num_vertices(graph));
using boost::make_iterator_range;
for (auto e : make_iterator_range(out_edges(vertex, graph)))
graph[target(e, graph)]._isVisible = false;
for (auto e : make_iterator_range(in_edges(vertex, graph)))
graph[source(e, graph)]._isVisible = false;
}
Live Demo
Live On Compiler Explorer
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/property_map/function_property_map.hpp>
struct VertexProps {
bool _isVisible = true;
};
using BGType = boost::adjacency_list< //
boost::vecS, //
boost::vecS, //
boost::bidirectionalS, //
VertexProps>;
using BGV = BGType::vertex_descriptor;
void hide_neighbours(BGV vertex, BGType& graph) {
assert(vertex < num_vertices(graph));
using boost::make_iterator_range;
for (auto e : make_iterator_range(out_edges(vertex, graph)))
graph[target(e, graph)]._isVisible = false;
for (auto e : make_iterator_range(in_edges(vertex, graph)))
graph[source(e, graph)]._isVisible = false;
}
int main() {
BGType graph(8);
add_edge(1, 5, graph);
add_edge(5, 3, graph);
add_edge(3, 7, graph);
add_edge(7, 4, graph);
add_edge(6, 5, graph);
add_edge(2, 5, graph);
auto annotate = boost::make_function_property_map<BGV>([&graph](auto v) {
auto id = std::to_string(v);
return graph[v]._isVisible ? id : "(" + id + ")";
});
print_graph(graph, annotate, std::cout << std::boolalpha);
hide_neighbours(4, graph);
print_graph(graph, annotate, std::cout << "\nNeigbours of 4 hidden:\n");
hide_neighbours(5, graph);
print_graph(graph, annotate, std::cout << "\nNeigbours of 5 hidden:\n");
}
Prints
0 -->
1 --> 5
2 --> 5
3 --> 7
4 -->
5 --> 3
6 --> 5
7 --> 4
Neigbours of 4 hidden:
0 -->
1 --> 5
2 --> 5
3 --> (7)
4 -->
5 --> 3
6 --> 5
(7) --> 4
Neigbours of 5 hidden:
0 -->
(1) --> 5
(2) --> 5
(3) --> (7)
4 -->
5 --> (3)
(6) --> 5
(7) --> 4
Note that if you specify an invalid vertex you'll get:
sotest: /home/sehe/Projects/stackoverflow/test.cpp:17: void hide_neighbours(BGV, BGType&): Assertion `vertex < num_vertices(graph)' failed.
OTHER HINTS
If the above doesn't immediately remove/expose the issue then you have Undefined Behaviour. Perhaps graph is indeed a dangling reference, or graph has been modified in illegal ways (e.g. removing vertices that weren't cleared).
Feel free to post another question with more relevant code if you need help finding such causes.
|
71,935,073 | 71,935,182 | How can I inspect the default copy/move constructors/assignment operators? | How do I find out what exactly my classes' default constructors, destructors, and copy/move constructors/assignment operators do?
I know about the rule of 0/3/5, and am wondering what the compiler is doing for me.
If it matters, I'm interested in >=C++17.
| The implicitly-defined copy constructor
... performs full member-wise copy of the object's bases and non-static members, in their initialization order, using direct initialization...
For a simple structure:
struct A
{
int x;
std::string y;
double z;
};
The copy-constructor would be equivalent to:
A::A(A const& otherA)
: x(otherA.x), y(otherA.y), z(otherA.z)
{
}
|
71,935,089 | 71,935,263 | Does Golang have something like C++'s decltype? | C++ has decltype(expr). You can declare an object of type of some other expression. For example:
decltype('c') a[4] will declare an array of 4 chars. This is a toy example, but this feature can be useful. Here is some Go code for a UDP server:
conn, err := net.ListenUDP("udp", udp_addr)
...
defer conn.Close()
...
_, err = conn.WriteToUDP(data, addr)
The important thing is that I know what I can do with the (type of the) result a function (in this case, with a connection, the result of ListenUDP), but I don't know what this type is. Here, because of Go's type inference, I don't need to know. But if I want to create 5 connections, then I'd like an array of 5 "results of ListenUDP". I am not able to do that. The closest I've got is:
ret_type := reflect.TypeOf(net.DialUDP)
first_param_type := reflect.TypeOf(ret_type.Out(0))
my_arr := reflect.ArrayOf(4, first_param_type)
my_arr[0] = nil
But the last line doesn't work. Is there a way to do it in Go?
| Go does not have a compile-time equivalent to C++'s decltype.
But Go is a statically typed language: even though there's type inference in case of short variable declaration, the types are known at compile time. The result type(s) of net.ListenUDP() are not visible in the source code, but you can look it up just as easily, e.g. it takes 2 seconds to hover over it with your mouse and your IDE will display the signature. Or check online. Or run go doc net.ListenUDP in a terminal.
Signature of net.ListenUDP() is:
func ListenUDP(network string, laddr *UDPAddr) (*UDPConn, error)
So the array type to hold 5 of the returned connections is [5]*net.UDPConn. Also note that it's better and easier to use slices instead of arrays in Go.
So instead I suggest to use a slice type []*net.UDPConn. If you need a slice to hold 5 connections, you can make it using the builtin make() like this: make([]*net.UDPConn, 5).
If you really need to do this dynamically, at runtime, yes, reflection can do this. This is how it could look like:
funcType := reflect.TypeOf(net.ListenUDP)
resultType := funcType.Out(0)
arrType := reflect.ArrayOf(4, resultType)
arrValue := reflect.New(arrType).Elem()
conn := &net.UDPConn{}
arrValue.Index(0).Set(reflect.ValueOf(conn))
fmt.Println(arrValue)
This will output (try it on the Go Playground):
[0xc00000e058 <nil> <nil> <nil>]
See related: Declare mutiple variables on the same line with types in Go
|
71,935,109 | 71,935,759 | c++ selection sort with separate minimum index function | Hi I'm doing a problem for my c++ class where we are to create a generic selection sort function for all types with separate function that finds minimum index. I tried to modify selection sort function that uses two for loops by separating the two for loops into two separate functions.
I tried different ways to approach this problem but I just don't get what I am doing wrong. Please help.
#include <vector>
#include <random>
#include <iostream>
#include<stdexcept>
#include<time.h>
#include <valarray>
using namespace std;
template <typename T>
unsigned min_index(const vector<T> &vals, unsigned index){
auto min = index;
for(auto i = index +1; i != vals.end();i++){
if(*i < *min)
min = i;
}
return min;
}
template <typename T>
void selection_sort(vector<T> &vals){
for(auto i=vals.begin(); i!=vals.end(); i++){
auto min = min_index(vals, i);
swap(*i, *min);
}
}
| You're trying to develop a positional-index based min_index (which is dreadfully broken itself), then use it within an iterator-based selection sort.
template <typename T>
unsigned min_index(const vector<T> &vals, unsigned index)
{
auto min = index; // min is 'unsigned' like 'index'
// this loop is nonsense.
// 'i' is unsigned (because 'index' is unsigned)
// 'vals.end()' is an iterator, not an unsigned, therefore...
// 'i != vals.end()` is nonsense.
// 'min' is also unsigned, therefore...
// both *i and *min are nonsense.
for(auto i = index +1; i != vals.end();i++)
{
if(*i < *min)
min = i;
}
return min;
}
Later on, in your selection-sort...
template <typename T>
void selection_sort(vector<T> &vals){
// here 'i' is an iterator
for(auto i=vals.begin(); i!=vals.end(); i++)
{
// here you're trying to pass an iterator to a function
// expecting an unsigned.
auto min = min_index(vals, i);
// and the above function is returning an unsigned
// therefore *min is nonsense.
swap(*i, *min);
}
}
In short, neither of those functions can possibly compile, much less work.
You need to choose one or the other and stick with it. This is C++, so the easiest to implement is likely an iterator version. As a bonus, it also ends up being the most generic (there are iterators literally everywhere in modern C++). For example, the min_index, rewritten as min_iter, could look like this:
template<class Iter>
Iter min_iter(Iter beg, Iter end)
{
auto min = beg;
for (; beg != end; ++beg)
{
if (*beg < *min)
min = beg;
}
return min;
}
Now you can use that in an iterator-based selection-sort as well:
template <class Iter>
void selection_sort(Iter beg, Iter end)
{
for (; beg != end; ++beg)
std::iter_swap(beg, min_iter(beg, end));
}
And finally, you can front this with a generic sequence abstraction by utilizing the general std::begin and std::end functions from the standard library:
template<class Seq>
void selection_sort(Seq& seq)
{
selection_sort(std::begin(seq), std::end(seq));
}
Now you can pass a vector, a deque, an array, etc. Pretty much any sequence container instance will work, so long as the underlying element type supports operator < either natively or by overload.
Position Based
A similar solution specific to your container type (a vector) and ordinal position rather than iterators would be something like this:
template <typename T>
unsigned min_index(const std::vector<T> &vals, unsigned index)
{
unsigned min = index;
for (unsigned i = index + 1; i < vals.size(); i++)
{
if (vals[i] < vals[min])
min = i;
}
return min;
}
template <typename T>
void selection_sort(std::vector<T> &vals)
{
for (unsigned i = 0; i < vals.size(); i++)
std::swap(vals[i], vals[min_index(vals, i)]);
}
|
71,935,361 | 71,943,808 | question about VkPhysicalDeviceVulkan12Features | I ran into an issue when adding features to a physical device using bootstrap https://github.com/charles-lunarg/vk-bootstrap. Doing so gives me assertion failed
Assertion failed: m_init, file \vkbootstrap\VkBootstrap.h, line 132
I understand that this could indicate a bug within the vk-bootstrap source, but I wanted to rule out that it's my own fault. Here is the code snippet which im using to add (empty)VkPhysicalDeviceVulkan12Features into physical device and I wanted to know if I'm intializing it correctly
VkPhysicalDeviceVulkan12Features feat;
feat.pNext = nullptr;
feat.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
vkb::PhysicalDeviceSelector selector{ vkb_inst };
vkb::PhysicalDevice physicalDevice = selector
.set_minimum_version(1, 2)
.set_surface(_surface)
.set_required_features_12(feat)
.select()
.value();
| You are not checking Results for errors.
Probably should be something like:
vkb::PhysicalDeviceSelector selector{ vkb_inst };
auto maybe_device = selector.select();
if( !maybe_device ) panic( maybe_device.error() );
vkb::PhysicalDevice device = maybe_device.value();
|
71,935,601 | 71,935,645 | Why member of class type needs initialization? | I am reading about constructors in C++. I came across this example:
#include <iostream>
using namespace std;
class NoDefault
{
public:
NoDefault(const std::string&);
};
struct A
{
NoDefault my_mem;
};
int main()
{
A a;
return 0;
}
It is giving this message on compilation:
main.cpp:26:7: error: use of deleted function ‘A::A()’
I can get a intuitive feeling that the default ctor is deleted because there is a member of class type inside the struct A. I want to ask why there is a necessity to initialize the class type member? Can we not leave it uninitialized?
Maybe very trivial question, but I am curious about the thinking behind designing it that way? I am new to OOP.
| A a; performs default initialization; a gets default-initialized, and its member my_mem gets default-initialized too. For class type, that means the default constructor will be used for the initialization but NoDefault doesn't have it, which leads to the error. (Behaviors are different for built-in types. In default-initialization they might be initialized to indeterminate values.)
|
71,935,719 | 72,022,747 | Is there a way to set jumbo frame with C++ in Windows? | My C++ application uses Gige camera on many various Windows 10 PC.
So I wanna set jumbo frame of LAN card of PC programmatically. (when the process starts it is enabled and disabled when the end of process.)
any helps?
| Thanks to @SimonMourier, I could write power shell command for enables jumbo frames and 1gbps duplex.
// enables.ps1
// Query all network adapter which has 'jumbo frame' property and set it as 9014 bytes.
$jumboFramesList = (Get-NetAdapterAdvancedProperty -RegistryKeyword "*JumboPacket")
foreach($item in $jumboFramesList) {
Set-NetAdapterAdvancedProperty -DisplayName $item.DisplayName -RegistryValue "9014"
}
// Query all network adapter which has 'speed & duplex' property and set it as 1.0 gbps duplex.
$speedDuplexList = (Get-NetAdapterAdvancedProperty -RegistryKeyword "*SpeedDuplex")
foreach($item in $speedDuplexList ) {
Set-NetAdapterAdvancedProperty -DisplayName $item.DisplayName -RegistryValue "6"
// Registry 6 means "1.0 Gbps duplex"
}
// reset.ps1
// Reset all network adapters' properties of 'jumbo frames' and 'speed & duplex'
$jumboFramesList = (Get-NetAdapterAdvancedProperty -RegistryKeyword "*JumboPacket")
foreach($item in $jumboFramesList) {
Reset-NetAdapterAdvancedProperty -Name * -DisplayName $item.DisplayName
}
$speedDuplexList = (Get-NetAdapterAdvancedProperty -RegistryKeyword "*SpeedDuplex")
foreach($item in $speedDuplexList) {
Reset-NetAdapterAdvancedProperty -Name * -DisplayName $item.DisplayName
}
and I could run above script files in my application when I need it.
|
71,935,796 | 71,935,980 | No need to define functions in header files for inlining? | In order for the compiler to inline a function call, it needs to have the full definition. If the function is not defined in the header file, the compiler only has the declaration and cannot inline the function even if it wanted to.
Therefore, I usually define short functions that I imagine the compiler might want to inline in header files.
With the whole-program optimization (/LTCG and /GL), is there no longer need for defining functions in header files to allow them to be inlined?
Are there other reasons to define functions in header files, except in some cases with templates?
| One reason is because you want to distribute single-header libraries, like STB.
Also, linking is notoriously slow, even with new linkers like gold and LLD. So, you might want to avoid linking, and instead include everything in a single file.
This can go beyond linking and just function definitions. The idea is to generally include everything only once to reduce compile-time, because the C++ compilation model is quite bad and slow, and part of the reason is that things are re-compiled. This is the idea of the unity build.
If you think that a unity build sounds super dumb, consider that Ubisoft (at least used to) use it.
|
71,937,005 | 71,965,888 | Application Error Visual Studio 2022: Database Interface Project successfully builds but does not run | I'm receiving the message below when I attempt to start the Local Windows Debugger on this project in Visual Studio 2022 . I had some earlier challenges adding and linking the additional include libraries and files for MySql as well as some earlier notifications about missing .dll files. I thought these were resolved since I was able to successfully build. What do I need to check to start trying to fix this? Let me know if any additional information is needed.
| I was able to resolve the issue by re-writing the project from scratch on my laptop, starting with an empty C++ project. In the course of doing that, I did run into some of the same messages regarding missing .dll files. This was resolved by copying and pasting these into the appropriate /debug folder for the project directory. As suggested, I did implement the scan for corrupt files, which fortunately did not turn up any issues. Once this was completed, I achieved a successful build and execution of the program.
|
71,937,037 | 71,940,794 | LDAP connection with AD using C++ | I'm trying to just make an LDAP connection with Active directory to get the list of users. But I'm not even able to compile the simple code for just authentication with the AD using C++.
I have tried many C++ example programs but only got compilation errors. I really just want to connect with AD using C++ without any errors. So can you please tell me what I'm doing wrong in this code which attempts to add a new user to the AD. I have added the environment details, code and errors below for reference.
CODE:
#ifndef UNICODE
#define UNICODE
#endif
#pragma comment(lib, "netapi32.lib")
#include <windows.h>
#include <lm.h>
#include<iostream>
int main()
{
USER_INFO_1 ui;
DWORD dwLevel = 1;
DWORD dwError = 0;
NET_API_STATUS nStatus;
//
// Set up the USER_INFO_1 structure.
// USER_PRIV_USER: name identifies a user,
// rather than an administrator or a guest.
// UF_SCRIPT: required
//
ui.usri1_name = L"username";
ui.usri1_password = L"password";
ui.usri1_priv = USER_PRIV_USER;
ui.usri1_home_dir = NULL;
ui.usri1_comment = NULL;
ui.usri1_flags = UF_SCRIPT;
ui.usri1_script_path = NULL;
//
// Call the NetUserAdd function, specifying level 1.
//
nStatus = NetUserAdd(L"servername",
dwLevel,
(LPBYTE)&ui,
&dwError);
//
// If the call succeeds, inform the user.
//
if (nStatus == NERR_Success)
fwprintf(stderr, L"User %s has been successfully added on %s\n",
L"user", L"dc");
//
// Otherwise, print the system error.
//
else
fprintf(stderr, "A system error has occurred: %d\n", nStatus);
return 0;
}
ERROR:
PS C:\Users\user\Desktop\Sandbox\Cpp> cd "c:\Users\user\Desktop\Sandbox\Cpp\" ; if ($?) { g++ ldap.cpp -o ldap } ; if ($?) { .\ldap }
ldap.cpp: In function 'int main()':
ldap.cpp:22:20: warning: ISO C++ forbids converting a string constant to 'LPWSTR' {aka 'wchar_t*'} [-Wwrite-strings]
22 | ui.usri1_name = L"username";
| ^~~~~~~~~~~
ldap.cpp:23:24: warning: ISO C++ forbids converting a string constant to 'LPWSTR' {aka 'wchar_t*'} [-Wwrite-strings]
23 | ui.usri1_password = L"password";
| ^~~~~~~~~~~
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\user-1~1\AppData\Local\Temp\ccByZfCT.o:ldap.cpp:(.text+0xfb): undefined reference to `NetUserAdd'
collect2.exe: error: ld returned 1 exit status
My system run on Windows 10 64bit
Installed MSYS with MinGW64 compiler.
| I'm no C++ or MinGW expert, but I have a little experience, and I did some Googling. This is the only error:
undefined reference to `NetUserAdd'
The others are warnings.
By your output, it looks like your command to compile is this:
g++ ldap.cpp -o ldap
Try adding -lnetapi32 to the end of that:
g++ ldap.cpp -o ldap -lnetapi32
If you want to resolve those warnings, I think you can declare variables for the username and password rather than assigning literals directly to the struct:
wchar_t username[] = L"username";
wchar_t password[] = L"password";
ui.usri1_name = username;
ui.usri1_password = password;
|
71,937,633 | 71,939,654 | Error on pass template argument through function | I write some utility to traits the return type of a function As the code shown. why the traits can't work after pass the function into traits function?
Thanks for your great help.
template <class>
struct FunctionHelper;
template <class R, class... ArgsT>
struct FunctionHelper<R(ArgsT...)> {
typedef R type;
};
template <class R, class... ArgsT>
struct FunctionHelper<R *(ArgsT...)> {
typedef R type;
};
int sum(int a, int b);
int *sum1(int a, int b);
template <class Func>
void traits(Func func) {
typename FunctionHelper<Func>::type value;
}
int main() {
traits(sum); // Here is error. error C2027: use of undefined type
traits<decltype(sum)>(sum); // Here works fine
FunctionHelper<decltype(sum)>::type value; // Here works fine
}
The error message in MSVS 14.1 shows below
[build] E:\source\cpp\function_traits\main.cpp(17,34): error C2027: use of undefined type 'FunctionHelper<Func>' [E:\source\cpp\function_traits\build\func_traits.vcxproj]
[build] with
[build] [
[build] Func=int (__cdecl *)(int,int)
[build] ]
[build] E:\source\cpp\function_traits\main.cpp(17): message : see declaration of 'FunctionHelper<Func>' [E:\source\cpp\function_traits\build\func_traits.vcxproj]
[build] with
[build] [
[build] Func=int (__cdecl *)(int,int)
[build] ]
[build] E:\source\cpp\function_traits\main.cpp(21): message : see reference to function template instantiation 'void traits<int(__cdecl *)(int,int)>(Func)' being compiled [E:\source\cpp\function_traits\build\func_traits.vcxproj]
[build] with
[build] [
[build] Func=int (__cdecl *)(int,int)
[build] ]
[build] E:\source\cpp\function_traits\main.cpp(17,1): error C2065: 'type': undeclared identifier [E:\source\cpp\function_traits\build\func_traits.vcxproj]
[build] E:\source\cpp\function_traits\main.cpp(17,39): error C2146: syntax error: missing ';' before identifier 'value' [E:\source\cpp\function_traits\build\func_traits.vcxproj]
[build] E:\source\cpp\function_traits\main.cpp(17,39): error C2065: 'value': undeclared identifier [E:\source\cpp\function_traits\build\func_traits.vcxproj]
| As noted in the comments,
template <class R, class... ArgsT>
struct FunctionHelper<R *(ArgsT...)> {
typedef R type;
};
specializes FunctionHelper for a function returning a pointer, not for a
function pointer.
As for
traits(sum); // Here is error. error C2027: use of undefined type
I suggest you have a look at Template argument deduction.
Since your parameter func is not a reference type, here:
template <class Func>
void traits(Func func) {
typename FunctionHelper<Func>::type value;
}
The following rule applies:
Before deduction begins, the following adjustments to P and A are made:
If P is not a reference type,
a. [...]
b. otherwise, if A is a function type, A is replaced by the pointer type obtained from function-to-pointer conversion;
template<class T>
void f(T);
// ...
void b(int);
f(b); // P = T, A = void(int), adjusted to void(*)(int): deduced T = void(*)(int)
So, your Func type is deduced as int(*)(int,int) and compilation fails because there's no specialization of FunctionHelper for a function pointer.
You may get you behavior you expect by changing traits to
template <class Func>
void traits(Func const& func) {
typename FunctionHelper<Func>::type value;
}
|
71,938,530 | 71,938,754 | Add an executable to registry in order to run at startup | I want to add a value to the Run key of the Windows Registry in order for my program to run at startup. I have written the following code. It compiles and links successfully. And when I debug the project, it doesn't give any errors. But, my key doesn't get added to the Registry.
int wmain(int argc, wchar_t* argv[])
{
HKEY key_handle;
std::wstring start_name = L"MyApplication";
std::wstring exe_path = L"C:\\Users\\user\\AppData\\Roaming\\Microsoft\\Windows\\MyApp.exe";
LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_WRITE, &key_handle);
if (ERROR_SUCCESS == result)
{
result = RegSetValueEx(key_handle, start_name.c_str(),
0,
REG_SZ,
(unsigned char*)exe_path.c_str(),
exe_path.length() * sizeof(wchar_t));
if (result != ERROR_SUCCESS)
{
printf("Error setting key %d\n", GetLastError());
}
}
else
{
printf("Error opening key %d\n", GetLastError());
}
RegCloseKey(key_handle);
return 0;
}
| You should first create a key there and set a value for it. Use the following code snipts which add a key and a value to the run registry. It has been written with C++ and classes.
#include <Windows.h>
#include <iostream>
class startup_management
{
private:
HKEY m_handle_key = NULL;
LONG m_result = 0;
BOOL m_status = TRUE;
DWORD m_registry_type = REG_SZ;
wchar_t m_executable_path[MAX_PATH] = {};
DWORD m_size = sizeof(m_executable_path);
BOOL m_success = TRUE;
public:
BOOL check(PCWSTR arg_application_name)
{
m_result = RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_READ, &m_handle_key);
m_status = (m_result == 0);
if (m_status)
{
m_result = RegGetValueW(m_handle_key, NULL, arg_application_name, RRF_RT_REG_SZ, &m_registry_type, m_executable_path, &m_size);
m_status = (m_result == 0);
}
if (m_status)
{
m_status = (wcslen(m_executable_path) > 0) ? TRUE : FALSE;
}
if (m_handle_key != NULL)
{
RegCloseKey(m_handle_key);
m_handle_key = NULL;
}
return m_status;
}
BOOL add(PCWSTR arg_application_name, PCWSTR arg_path_executable, PCWSTR arg_argument_to_exe)
{
const size_t count = MAX_PATH * 2;
wchar_t registry_value[count] = {};
wcscpy_s(registry_value, count, L"\"");
wcscat_s(registry_value, count, arg_path_executable);
wcscat_s(registry_value, count, L"\" ");
if (arg_argument_to_exe != NULL)
{
wcscat_s(registry_value, count, arg_argument_to_exe);
}
m_result = RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, (KEY_WRITE | KEY_READ), NULL, &m_handle_key, NULL);
m_success = (m_result == 0);
if (m_success)
{
m_size = (wcslen(registry_value) + 1) * 2;
m_result = RegSetValueExW(m_handle_key, arg_application_name, 0, REG_SZ, (BYTE*)registry_value, m_size);
m_success = (m_result == 0);
}
if (m_handle_key != NULL)
{
RegCloseKey(m_handle_key);
m_handle_key = NULL;
}
return m_success;
}
};
int wmain(int argc, wchar_t* argv[])
{
startup_management o_startup;
wchar_t executable_path[MAX_PATH];
GetModuleFileNameW(NULL, executable_path, MAX_PATH);
o_startup.add(L"Milad", executable_path, L"-foobar");
return 0;
}
Then check the following path:
Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
|
71,939,732 | 71,940,993 | perlin noise giving diffrent values for same point after player has moved | I am using perlin noise to generate a map for my game. This is then being drawn using marching squares. The values That are being input for the perlin noise function are relative to a 0,0 coordinate and then this is converted to a position on screen that can then be drawn to.
The problem is that when the player moves the image that is drawn to the screen is slightly different at the edges of the mesh this causes a flickering effect when the player is moving.
asteroids_in_range(player.x-WIDTH/2,player.x+WIDTH/2,player.y-HEIGHT/2,player.y+HEIGHT/2,16);
int get_asteroid_case(float x, float y, float box_size)
{
/*get the case for the box with the bottom left corner
at location x,y and size of box_size*/
int count = 0;
if(perlin.GetValue(x, y, 0.1) > THRESHHOLD)
{
count += 8;
}
if(perlin.GetValue(x+box_size, y, 0.1) > THRESHHOLD)
{
count += 4;
}
if(perlin.GetValue(x+box_size, y+box_size, 0.1) > THRESHHOLD)
{
count += 2;
}
if(perlin.GetValue(x, y+box_size, 0.1) > THRESHHOLD)
{
count += 1;
}
return count;
}
void asteroids_in_range(float xmin, float xmax, float ymin, float ymax, float grid_size)
{
int num;
for(float x = xmin; x <= xmax; x+=grid_size)
{
for(float y = ymin; y <= ymax; y+=grid_size)
{
num = get_asteroid_case(x, y, grid_size);
if(num != 0 && num != 15)
render_asteroids(num,x,y, 1);
}
}
}
Images with the player one pixel apart as can be seen, there are subtle differences on the fringes of the generated meshes.
| Your problem is you are getting different noise values because you are getting the noise at different points. Don't do that. Make it the same points - the ones on the grid.
Let's say grid_size is 10 (pixels) and WIDTH is 100 (pixels) and the player is at 0,0. You are getting the noise at -50,-50, and -40,-50, and -30,-50, and so on.
Now say the player moves 3 pixels right. You are getting the noise at -47,-50, and -37,-50, and -27,-50, and so on. Obviously you get different noise values, because you asked for different noise values!
Instead you should round the noise coordinates to the grid - to multiples of grid_size. Your code can easily be adapted by rounding xmin and xmax and ymin and ymax before the grid rendering - for example:
xmin = floor(xmin / grid_size) * grid_size;
xmax = ceil(xmax / grid_size) * grid_size;
// same for y
The min coordinate is rounded down, and the max coordinate is rounded up, to make sure the entire screen is still inside the rendered coordinates.
|
71,941,102 | 71,941,178 | Instance of C++ template class as a member of another template class | Let's say I have following templated C++ class
#include <cstdint>
template <uint32_t NO_POINTS>
class A
{
public:
struct Point
{
float x;
float y;
};
A(const Point (&points)[NO_POINTS])
{
for (uint32_t point = 0; point < NO_POINTS; point++) {
table[point] = points[point];
}
}
private:
Point table[NO_POINTS];
};
and I would like to use an instance of this class as a private member of the following class:
#include "A.h"
template <uint32_t NO_LUT_POINTS>
class B
{
public:
B(A<NO_LUT_POINTS>::Point (&table)[NO_LUT_POINTS]) : lut(table){}
private:
A<NO_LUT_POINTS> lut;
};
#include "B.h"
int main(int argc, char** argv) {
B<4> foo({{1326.0, 25.0}, {1601.0, 30.0}, {1922.0, 35.0}, {2293.0, 40.0}});
return 0;
}
I have attempted to compile this code but the compiler reports following error
A<NO_LUT_POINTS>::Point is not a type. I don't understand what the reason for this error is. Can anybody explain to me why the compiler reports this error?
| This is a common mistake with types nested in template classes. You need to add typename to tell the compiler that Point is a type.
...
public:
B(typename A<NO_LUT_POINTS>::Point const (&table)[NO_LUT_POINTS]) : lut(table){}
...
Beyond solving your problem, however, please notice that Point doesn't depend on the template parameters of A, so you should not nest it in that class. This would remove the necessity for adding typename.
|
71,941,270 | 71,941,897 | Check for existence of nested type alias and conditionally set type alias | I wonder how to conditionally set a type alias, based on the existance of a type alias in input argument like this.
struct a { using type = int; }
template <typename T> struct wrapper {
using inner_t = ???how???; // if T::type exists, use T::type, else T
};
static_assert(std::is_same<wrapper<int>::inner_t, int>, "expected int");
static_assert(std::is_same<wrapper<a>::inner_t, int>, "expected inner type: int");
One naive attempt is like std::conditional<std::is_class<T>, T::type, T> if the existence of a type alias is a prerequisite, but is far from being safe, lacking a check for something like is_alias_present<T, type>. Besides that T::type is potentially not existing for all types resulting in a compiler error.
Apearently std::experimental::is_detected looks promising, but unfortunately not an option for now.
Not sure if metaprogramming libraries like boost::mp11 or boost::hana are a good approach to get that done.
| There are 2 things, the traits to detect presence, and the lazy evaluation.
In C++20, the traits can be done easily with requires
template <typename T>
concept has_type = requires { typename T::type; }
Then the lazy evaluation:
template <typename T> struct wrapper {
using inner_t = std::conditional_t<has_type<T>, T, std::type_identity<T> >::type;
};
|
71,941,282 | 71,941,327 | Is it a data-race when several thread *read* the same memory at the same time? | cppreference.com says:
Threads and data races
When an evaluation of an expression writes to a memory location and
another evaluation reads or modifies the same memory location, the
expressions are said to conflict. A program that has two conflicting
evaluations has a data race unless...
This speaks about the scenario of 'thread1-write thread2-read' (W-R) and about the scenario of 'thread1-write thread2-write' (W-W).
What about 'thread1-read thread2-read' (R-R)?
| No. Multiple threads reading memory sequenced is not a data race as long as no thread is writing unsequenced in that memory location.
That scenario was probably left out of that description of data races, because that scenario is not a data race.
|
71,941,530 | 71,941,813 | Call constructor on uninitialized memory in C++ | I have some legacy C++ (10+ years old) that I am trying to compile where there is a buffer/allocator, that is used to get some memory for a new object. Then a function, std::_Construct, is called that I assume is used to call the constructor for the object (since the allocator only returns a void*). But I suspect that it is only a feature of an older version of Visual Studio (I can't find anything from before VS2015), so I am wondering: How can I call the constructor on a piece of uninitialized memory that I have casted to the class I'm trying to construct?
Here is a little pseudo-code of what I'm trying to achieve:
BufferManagementClass mBuffMan; // "allocator"
class A { ... };
A* initObject() {
A* pA = static_cast<A*>(mBuffMan.GetBuffer(sizeof(A))); // GetBuffer returns void*, so I cast it.
if (pA == NULL)
return NULL;
/*
How do I call the constructor of the memory pA points to here?
I assume that is needed before I can call any methods in pA?
*/
pA->someFunc();
pA->someOtherFunc();
return pA;
}
I have converted the project to C++14 (since that's the earliest standard version that VS2019 supports) by the way.
| There is no std::_Construct in standard library. The underscore + upper case prefix implies that this is a language extension or implementation detail of the standard library. Since it has disappeared in version change, it was probably the latter.
The standard way to create an object in uninitalised storage that has been available for 24+ years is to use placement-new syntax:
void* memory = mBuffMan.GetBuffer(sizeof(A))
A* aP = new(memory) A(/*constructor arguments*/);
Since C++11, an alternative is to std::allocator_traits::construct. This has the advantage of having become constexpr since C++20. This approach is conventional when you use an allocator, which is quite typical when the allocation and object creation is separated:
using ExampleAlloc = std::allocator<A>;
using AT = std::allocator_traits<ExampleAlloc>;
ExampleAlloc alloc{};
A* aP = AT.allocate(alloc, 1);
AT.construct(alloc, memory, /*constructor arguments*/);
Same was possible pre C++11 using std::allocator::construct, but that has been deprecated in C++17 in favour of using std::allocator_traits and removed in C++20.
Another alternative, when you are dealing with creation of multiple object into the memory, is to use std::uninitialized_copy, std::uninitialized_fill, std::uninitialized_move (C++17), std::uninitialized_default_construct (C++17), std::uninitialized_value_construct (C++17):
extern A value;
A* aP = AT.allocate(alloc, count);
std::uninitialized_fill_n(aP, count, value);
Lastly, C++20 added yet another alternative, std::construct_at.
|
71,941,934 | 71,942,138 | Should I convert C static function to private member function or free function in unnamed namespace? | I want to update some C legacy code to C++. Suppose I had something similar to this code in C:
//my_struct.h
typedef struct myStruct {
//some members go here
} myStruct;
int f1(myStruct*);
void f2(myStruct*);
//my_struct.c
#include "my_struct.h"
static int helper(myStruct* st)
{
return 21;
}
int f1(myStruct* st)
{
return helper(st);
}
void f2(myStruct* st) {}
If I update it to the following in CPP:
//myStruct.h
struct myStruct {
int f1();
void f2();
private:
int helper();
};
//myStruct.cpp
int myStruct::f1(){
return helper();
}
void myStruct::f2(){}
int myStruct::helper(){
return 21;
}
What is the impact of converting the global static C function to a private member function in C++?
What would be the pros/cons (regarding compilation, linking, runtime) between the previous approach and the following one? I didn't use the parameter inside the function to make the example short (If it is not used I read in other questions that it should probably go to the anonymous namespace).
//myStruct.h
struct myStruct {
int f1();
void f2();
}
//myStruct.cpp
namespace{
int helper(myStruct *st){
return 21;
}
}
int myStruct::f1(){
return helper(this);
}
void myStruct::f2(){}
|
What is the impact of converting the global static C function to a private member function in C++?
The impact is that you've made a (private, internal) implementation detail of your module part of the (public) interface.
What would be the pros/cons (regarding compilation, linking, runtime) between the previous approach and the following one?
Cons:
you've added semantic noise to your interface
ie, there's more for clients to read and think about, even though it shouldn't affect them,
changes to internal implementation details may require all clients of the interface to recompile, instead of just re-linking
ie, if you want to change helper, that now updates the public header and causes widespread recompilation of files that shouldn't be affected
Pros:
there are none.
It's idiomatic in C++ to add implementation-file-local details like helper to the anonymous namespace.
|
71,942,426 | 71,943,273 | How to ensure that my program prints the supplied values, not incorrect values? | Why my program is printing incorrect values, not the supplied values? Any help would be much appreciated.
Data
title1=q, year1=1, title2=w, year2=2
Code
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int getnumber ();
struct movies_t {
string title;
int year;
};
void printmovie (movies_t films);
int main ()
{
int z=getnumber ();
cout << "You will have to provide data for " << z << " films.\n";
//movies_t films [z];
vector<movies_t> films(z);
string mystr;
int n;
for (n=0; n<z; n++)
{
cout << "Enter title: ";
getline (cin,films[n].title);
cin.ignore();
cout << "Enter year: ";
getline (cin,mystr);
cin.ignore();
stringstream(mystr) >> films[n].year;
}
cout << "\nYou have entered these movies:\n";
for (n=0; n<z; n++)
printmovie (films[n]);
return 0;
}
void printmovie (movies_t films)
{
movies_t * pmovie;
pmovie = &films;
cout << pmovie->title;
cout << " (" << films.year << ")\n";
}
int getnumber ()
{
int i;
cout << "Please enter number of films: ";
cin >> i;
return i;
}
Output (obtained; incorrect)
Please enter number of films: 2
You will have to provide data for 2 films.
Enter title: q
Enter year: 1
Enter title: w
Enter year: 2
You have entered these movies:
(0)
(0)
Output (desired)
Please enter number of films: 2
You will have to provide data for 2 films.
Enter title: q
Enter year: 1
Enter title: w
Enter year: 2
You have entered these movies:
q (1)
w (2)
| Make a function that gets the value after = in each token.
string getValue(string field) {
auto pos = field.find('=');
return field.substr(pos + 1, field.find(',') - pos - 1);
}
Then all you need to do is:
for (n = 0; n < z; n++) {
string title, year;
assert(cin >> title >> year);
movies_t movie = {getValue(title), stoi(getValue(year))};
films.push_back(movie);
}
To use assert you need #include <cassert> at the top.
Update:
You need to ignore spaces, so add this to your program:
struct ctype_ : std::ctype<char>
{
static mask* make_table()
{
const mask* table = classic_table();
static std::vector<mask> v(table, table + table_size);
v[' '] &= ~space;
v[','] |= space;
return &v[0];
}
ctype_() : std::ctype<char>(make_table()) { }
};
And then do this just before the for loop:
cin.imbue(std::locale(cin.getloc(), new ctype_));
And then it should work.
2nd update:
for (n = 0; n < z; n++) {
string title, year;
cout << "Enter title: ";
assert(cin >> title);
cout << "Enter year: ";
assert(cin >> year);
movies_t movie = {getValue(title), stoi(getValue(year))};
films[n] = movie;
}
|
71,942,594 | 71,942,885 | How can I make a C++ typename nest itself and "infinitely" recurse? | Im trying to turn this piece of JSON into a C++ type using a neat little JSON parsing library I have created.
[
"a",
[
"b",
[
"c",
[
"d",
["... so on so forth"]
]
]
]
]
Currently, this is technically what the type would look like in C++, however this is obviously invalid as the typename cannot reference itself:
typename std::variant<std::string, std::vector<requirements_type>> requirements_type;
Is there any way to make an infinitely recurring typename that can handle this sort of structure?
| As mentioned in 463035818_is_not_a_number's answer
Instead of using a typename I can use a class that references itself:
struct RequirementArray {
std::variant<std::string, std::vector<RequirementArray>> self;
};
I can recurse through this by using this simple method:
void recurseAndOutput(RequirementArray array, int i) {
try {
std::vector<RequirementArray> requirementArrays = std::get<std::vector<RequirementArray>>(array.self);
for (RequirementArray requirementArray: requirementArrays) {
recurseAndOutput(requirementArray, i + 1);
}
} catch (std::bad_variant_access const & ignored) {
std::string string = std::get<std::string>(array.self);
printf("%s - %i", string.c_str(), i);
}
}
|
71,942,667 | 71,942,732 | C++ list functions not worling | I'm tryin to create a program that let me add elements in tail of a list and then prints them. It doesn't give me an error but he doesn't do anything. What am I doing wrong ?
#include<iostream>
using namespace std;
struct lista{
int val;
lista *next;
};
typedef lista* ptr_lista;
void tail_add(ptr_lista head, int valore){
if(head=NULL){
head=new lista;
head->val=valore;
head->next=NULL;
} else {
ptr_lista p=head;
while(p->next!=NULL){
p=p->next;
}
p->next=new lista;
p->next->val=valore;
p->next->next=NULL;
}
}
void print(ptr_lista p){
while(p!=NULL){
cout<<p->val<< " ";
p=p->next;
}
}
int main(){
ptr_lista m;
tail_add(m,5);
tail_add(m,6);
print(m);
}
| For starters the pointer m is not initialized and has an indeterminate value
ptr_lista m;
You need to initialize it
ptr_lista m = nullptr;
The function accepts the pointer by value
void tail_add(ptr_lista head, int valore){
So changing the parameter head within the function like
head=new lista;
has no effect on the original pointer m declared in main.
You need to declare the parameter as a reference to the pointer
void tail_add(ptr_lista &head, int valore){
The function can be defined the following way
void tail_add( ptr_lista &head, int valore )
{
ptr_lista new_lista_ptr = new lista { valore, nullptr };
if ( head == nullptr )
{
head = new_lista_ptr;
}
else
{
ptr_lista p = head;
while ( p->next ) p = p->next;
p->next = new_lista_ptr;
}
}
Pay attention to that it is not a good idea to introduce an alias for a pointer like
typedef lista* ptr_lista;
For example if you will write
const ptr_lista
then it means
lista * const
not
const lista *
that is required for the declaration of the parameter of the function print because it does not change nodes of the list.
|
71,943,060 | 71,943,268 | std::atomic passed as a const reference to a non-atomic type | Let's say I have this application:
#include <atomic>
#include <thread>
#include <iostream>
#include <chrono>
void do_something(const std::atomic<bool>& stop) {
while (!stop) {
std::cout << "Doing stuff..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
std::atomic<bool> stop { false };
std::thread wait([&stop] {
std::this_thread::sleep_for(std::chrono::seconds(10));
stop = true;
});
do_something(stop);
wait.join();
}
This works as expected. The main thread loops until the wait thread sets stop. As far as I know, there's no real issues with this application since it's using an std::atomic<bool> for synchronization between the threads.
However, I can break the application by changing the signature of do_something to this:
void do_something(const bool& stop);
This still compiles without any warnings, but the loop in do_something never exits. Conceptually, I understand why this happens. do_something is accepting a const reference to a non-atomic value, so it would be reasonable to optimize the function to something like:
void do_something(const bool& stop) {
if (!stop) {
while(true) {
std::cout << "Doing stuff..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
}
What's confusing to me is why the modified application compiles at all. I wouldn't expect to be able to pass an std::atomic value into a function expecting a const reference to a non-atomic type. I haven't looked at the standard, but I don't see anything on cppreference that suggests this conversion is allowed.
Am I misunderstanding something here? Is this just some quirk of std::atomic that's not obvious to me from the documentation?
| This is because there is an implicit conversion when you call
do_something(const bool &stop)
while passing an std::atomic<bool>
It translates to:
do_something(static_cast<bool>(stop.operator bool()));
As you can see here : https://en.cppreference.com/w/cpp/atomic/atomic/operator_T
You actually tell the compiler to load the value once, right at the time of the call.
|
71,943,098 | 71,943,235 | How to insert to std::map which is in std::multimap? | How can I insert another map into the map?
In the code, I try to copy the map from another.
multimap<string, map<size_t, size_t>> sorted;
for (auto itr = m_Items.begin(); itr != m_Items.end(); ++itr)
sorted.emplace(itr->first
, make_pair(itr->second.m_Date.m_Time, itr->second.m_Cnt)
);
| Assuming that you have m_Items as
struct Date {
std::size_t m_Time;
};
struct MyStruct
{
Date m_Date;
std::size_t m_Cnt;
};
std::multimap<std::string, MyStruct> m_Items;
then you need to
for (auto itr = m_Items.begin(); itr != m_Items.end(); ++itr)
sorted.emplace(itr->first, std::map<size_t, size_t>{ {itr->second.m_Date.m_Time, itr->second.m_Cnt} });
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Your map's value is again a map (i.e. std::map<size_t, size_t>) not a std::par. Therefore, you need to insert as above.
In c++17 with the help of structured binding declaration, and with a range based for loop(since c++11), you could write much intuitive:
for (const auto& [key, value] : m_Items)
sorted.emplace(key, std::map<size_t, size_t>{ {value.m_Date.m_Time, value.m_Cnt} });
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Here is a (short demo.)
However, if you only need an unsorted key-value as pair as entry in sorted, I would suggest a
std::multimap<std::string, std::pair<size_t, size_t>> sorted;
^^^^^^^^^^^^^^^^^^^^^^^^^^
instead there.
|
71,943,208 | 71,943,270 | user defined pointer wrapper and nullptr comparison does not call the operator I have provided | I want to compare if my my_ptr object is nullptr or not. I expected x == nullptr to call the following operator I have provided.
operator==(std::nullptr_t, const my_ptr<V>& r)
but it is not getting called. I don't see " == nullptr called" displayed on my output screen. And also if I uncomment the following line
my_ptr<int> x2{p2}
the result flips. I checked this behaviour in g++ and some online compilers
#include <iostream>
#include <type_traits>
#include <utility>
template <typename T>
class my_ptr
{
T* t = nullptr;
public:
my_ptr()
{
std::cout<<"\n No arguments constructor called\n";
}
my_ptr(std::nullptr_t)
{
std::cout<<"\n nullptr constructor called\n";
}
my_ptr(T* t_)
: t(t_)
{
std::cout<<"\n pointer constructor called\n";
}
operator const void*() const
{
std::cout<<"\n void param called ";
return t;
}
};
template <typename U, typename V>
bool operator==(const my_ptr<U>& l, const my_ptr<V>& r)
{
std::cout<<"\n == called\n";
return l.get() == r.get();
}
template <typename U, typename V>
bool operator==(std::nullptr_t, const my_ptr<V>& r)
{
std::cout<<"\n == nullptr called\n";
return false;
}
int main()
{
int *p;
my_ptr<int> x{p};
int *p2;
my_ptr<int> x2{p2}; //uncommenting this line changes the result value
std::cout<<"\n "<<int(x == nullptr)<<"\n";
return 0;
}
Output seen
with my_ptr x2{p2}; commented
pointer constructor called
void param called 0
with my_ptr x2{p2}; un-commented
pointer constructor called
pointer constructor called
void param called 1
| There are two issues with your operator.
template <typename U, typename V>
bool operator==(std::nullptr_t, const my_ptr<V>& r)
{
std::cout<<"\n == nullptr called\n";
return false;
}
It has a template argument U that cannot be deduced from the function parameters, hence you cannot use it with operator call syntax x == y.
Second, you defined operator==(std::nullptr_t,const my_ptr<V>&) but you call operator==(const my_ptr<V>&,std::nullptr_t). Before C++20 you need to explicitly implement the other order, also when the operator is symmetric.
You get expected output with this operator==:
template <typename V>
bool operator==(const my_ptr<V>&, std::nullptr_t)
{
std::cout<<"\n == nullptr called\n";
return false;
}
Live Demo
As pointed out by DaveS, since C++20, implementing operator(std::nullptr,cosnt my_ptr<V>&) is sufficient to call x == nullptr.
Last but not least, your code has undefined behavior due to using p and p1 when they are uninitialized.
|
71,943,346 | 71,943,493 | Can anyone make me understand why visual studio is giving me this warning for my c++ code? | I don't understand why the code has this warning:
C6385: Reading invalid data from 'arr': the readable size is '160'
bytes, but '200' bytes may be read.
This is a program to randomize numbers from the size of the string array and using these numbers to access elements within string array, 'arr'.
Here is the C++ code:
#include <iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
int main()
{
string arr[] = {"hey","music","ola","dang"};
int size = sizeof(arr) / sizeof(arr[0]);
int random;
srand(time(0));
for (int i = 1; i <= size; i++)
{
random = rand() % ((size+1-1)+1);
cout << random << "\t" << arr[random] << endl;
}
cout << endl;}
| Indexing of arrays in C++ starts from 0 instead of 1. This means that we can only safely access the elements with indices from 0 upto n - 1 where n is the number of elements in the array. Thus in your example, we can only safely access elements with index: 0, 1, 2 and 3. And if we use any other positive integer(that is greater than 3), then the program will have undefined behavior.
To solve this make sure that random always ranges from 0 upto 3 which you can do by changing random = rand() % ((size+1-1)+1); to:
random = rand() % (size);
So the modified code looks like:
int main()
{
string arr[] = {"hey","music","ola","dang"};
int size = sizeof(arr) / sizeof(arr[0]);
int random;
srand(time(0));
for (int i = 0; i < size; i++)//note the indexing starts from 0
{
random = rand() % ((size)); //changed this
cout << random << "\t" << arr[random] << endl;
}
cout << endl;
}
Demo
|
71,943,707 | 71,943,729 | Overwrite stack-allocated instance of a class | Consider the following code:
class A{
public:
A(){};
};
int main(){
A a = A();
std::cout << &a << std::endl;
a = A();
std::cout << &a << std::endl;
return 0;
}
Both addresses are the same. The behavior that I expected was that the second call to A() would overwrite the variable a by creating a new instance of A, thereby changing the new address of a.
Why is this so? Is there a way to statically overwrite a that I am not aware of?
Thank you!
|
Why is this so?
Within the scope of its lifetime, a variable is exactly one complete object (except in the case of recursion in which case there are multiple overlapping instances of the variable). a here is the same object from its declaration until the return of the function.
I expected was that the second call to A() would overwrite the variable a by creating a new instance of A,
It did that.
thereby changing the new address of a.
It didn't do that. The temporary object created by A() had a new address, but that temporary object was destroyed at the end of that full expression. a remained where it had been, and you invoked its assignment operator with the temporary object as the argument.
|
71,944,404 | 71,948,222 | VS 2022: "Unresolved external" error when calling methods that are defined outside of the class definition | So, I've tried to run the simplest C++ program imaginable in Visual Studio 2022:
main.cpp:
#include "TestClass.h"
int main() {
TestClass().testMethod();
}
TestClass.h:
#pragma once
class TestClass {
public:
void testMethod();
};
TestClass.cpp:
#include "TestClass.h"
inline void TestClass::testMethod() {
}
But for some reason, I get nothing but a linker error:
error LNK2019: unresolved external symbol "public: void __cdecl TestClass::testMethod(void)" (?testMethod@TestClass@@QEAAXXZ) referenced in function main
I know that there are tons of questions on Stack Overflow discussing that specific error, but I wasn't able to find anything that applied to my situation, except for this one, which doesn't have an answer.
All files are included in the project (everything was generated in Visual Studio), I do not get any warnings from IntelliSense, and every file on its own compiles just fine (using Ctrl+F7)
I have no clue what is going on and would appreciate any help.
| In C++ inline functions must have their body present in every translation unit from which they are called.
Removing inline doesn't change anything
Try to test it. I'm not the only one who proves that inline causes the lnk error. As
Sedenion says, it's a usage error.
I recommend reporting this wrong behavior to Developer Community and posting the link in this thread.
|
71,945,283 | 71,945,652 | Supress misra warning with function instead of macro | I want to ask if there is a way to suppress misra warnings using a custom function without having to write \\ Misra Warning Suppression (always the same derivation) everywhere.
I often use throw std::runtime_error("Custom Error") on many places in my code. Unfortunately, I have to do misra warning suppression. So I have to add \\ Misra Warning Suppression after every throw std::runtime_error("Custom Error");. In the code it is like this: throw std::runtime_error("Custom Error"); \\ Misra Warning Suppression. Since I literally have to use it everywhere with the same derivation, I thought about shortening it.
Here, the std::exception can be any error type. So I thought about using macros like this:
#define EXCEPTION_MISRA( TYPE, MESSAGE ) \
throw TYPE( MESSAGE) // Use Misra Suppression
int main()
{
EXCEPTION_MISRA( std::runtime_error, "Custom Error" );
return 0;
}
Unfortunately, macros are not really the yellow from the egg for my use case. Is there any way to do the same using functions? Kind of making your own xyz::throw function, where in the function the \\ Misra Warning Suppression is added?
Thank you!
| I don't use MISRA, but would a template work? Something like
template<class E>
[[ noreturn ]] void exception_misra(const std::string& message)
{
throw E(message); // Use Misra Suppression
}
called like so:
exception_misra<std::runtime_error>("Custom Error");
|
71,945,438 | 71,945,705 | c++ string subscript out of range/debug assertion failed | I am working on flipping a string of numbers. I get no errors or warnings when compiling, but after I input numbers, there popped out an error window where I can understand none of the words. Can someone help me?
my purpose is:to see, in an interval of numbers, how many numbers have is the same when turned 180 degrees? (e.g.8888, 6699, 90088006)
Enviroment:
OS: Windows 10, 64 bit
IDE: Visual studio community 2022
Error window:
code:
#include <iostream>
#include <string>
using namespace std;
int total = 0;
void numf(int n, string c) {
if (!(c.find('3') == 0 and c.find('4') == 0 and c.find('7') == 0 and
c.find('2') == 0 and c.find('5') == 0)) {
// reverse
string c2;
for (int i = 0; i < sizeof(c) / sizeof(c[0]); i++) {
c2[i] = c[sizeof(c) / sizeof(c[0]) - i - 1];
}
for (int i = 0; i < sizeof(c) / sizeof(c[0]); i++) {
if (c2[i] == '6') {
c2[i] = '9';
} else if (c2[i] == '9') {
c2[i] = '6';
}
}
if (c2 == c) {
total++;
}
}
return;
}
int main() {
int num, num2;
cin >> num >> num2;
for (int i = num; i <= num2; i++) {
string newnum = to_string(i);
numf(i, newnum);
}
cout << total;
return 0;
}
| For starters this if statement
if (!(c.find('3') == 0 and c.find('4') == 0 and c.find('7') == 0 and
c.find('2') == 0 and c.find('5') == 0)) {
does not make a sense.
It seems you are trying to exclude numbers that contain one of the listed digits.
In this case you should write
if ( c.find_first_of( "34725" ) == std::string::npos )
{
//...
The class std::string is not an array. So the expression sizeof(c) / sizeof(c[0]) in the loops like below also does not make a sense.
for (int i = 0; i < sizeof(c) / sizeof(c[0]); i++) {
c2[i] = c[sizeof(c) / sizeof(c[0]) - i - 1];
}
Moreover the object c2 is empty. So you may not use the subscript operator like c2[i].
You could just write instead of the loop
std::string c2( c.rbegin(), c.rend() );
This incorrect for loop
for (int i = 0; i < sizeof(c) / sizeof(c[0]); i++) {
if (c2[i] == '6') {
c2[i] = '9';
} else if (c2[i] == '9') {
c2[i] = '6';
}
}
can be changed for the following range-based for loop
for ( auto &ch : c2 )
{
if ( ch == '6')
{
ch = '9';
}
else if ( ch == '9' )
{
ch = '6';
}
}
Pay attention to that the first function parameter is not used within the function.
Also it is a bad idea to use the global variable total within the function. It will be much better if the function had the return type bool and returned true in case when a number satisfies the requirement.
If I have understood the assignment correctly then I would write the program something like the following.
#include <iostream>
#include <string>
#include <utility>
#include <algorithm>
bool numf( const std::string &s )
{
if ( s.find_first_of( "34725" ) == std::string::npos )
{
std::string s2( s.rbegin(), s.rend() );
for ( auto &c :s2 )
{
if (c == '9')
{
c = '6';
}
else if (c == '6')
{
c = '9';
}
}
return s == s2;
}
else
{
return false;
}
}
int main()
{
unsigned int num1 = 0, num2 = 0;
std::cin >> num1 >> num2;
std::tie( num1, num2 ) = std::minmax( { num1, num2 } );
unsigned int total = 0;
for (; num1 <= num2; ++num1)
{
total += numf( std::to_string( num1 ) );
}
std::cout << "total = " << total << '\n';
}
The program output might look like
60 99
total = 3
|
71,946,144 | 71,946,800 | Compute shared secret for ECDSA<ECP, SHA256> keys with Crypto++ | I'm trying to do the following:
Receive x and y coordinates of a EC public key
Generate a random EC public key
Compute the shared secret of the two keys
I'm stuck at the last step, from the Documentation is seems like I have to use ECDH<ECP>::Domain but nowhere is it explained how to convert the keys into the required SecByteBlock objects, how can I do this? Pseudocode follows.
std::string x = ...
std::string y = ...
auto make_curve = []{ return ASN1::secp256r1(); };
// Public key
ECDSA<ECP, SHA256>::PublicKey g_a;
g_a.Initialize(make_curve(),
ECP::Point {
Integer { x.data() },
Integer { y.data() }
});
// Private key
ECDSA<ECP, SHA256>::PrivateKey g_b;
g_b.Initialize(RANDOM_POOL, make_curve());
// Compute shared secret
ECDH<ECP>::Domain agreement { make_curve() };
SecByteBlock shared_secret_buf { agreement.AgreedValueLength() };
agreement.Agree(shared_secret_buf, ???, ???);
| The Wikipedia page shows you show to do this:
So first create a new key pair (you never generate just one private key):
ECDH < ECP >::Domain dhB( CURVE );
SecByteBlock privB(dhB.PrivateKeyLength()), pubB(dhB.PublicKeyLength());
dhB.GenerateKeyPair(rng, privB, pubB);
and then you can perform the key agreement like this:
if(!dhB.Agree(shared_secret_buf, privB, pubA))
throw runtime_error("Failed to reach shared secret (B)");
OK, so now you are left with one issue: encoding the public point. Fortunately that has been explained in the Wiki as well, here, basically you should just be able to use:
void ECP::EncodePoint(BufferedTransformation &bt, const Point &P, bool compressed)
Where your pubA buffer is put in &bt (I hope the input for &P is clear, use false for compressed).
Basically this returns a byte 04, then the concatenation of X and Y encoded with the size of the field (big endian).
Note that this just requires an ECP::Point and as the key pair generation also doesn't use ECDSA, that part of the code can be stripped out entirely. That's good, because ECDH is a different algorithm and using ECDSA could make the code less portable, e.g. when using the X25519 curve.
|
71,946,389 | 71,946,751 | C++ removing element in map in map | I have this program in which I store values in a map in this form.
map<string, map<int, CItem, cmpByCnt>> m_Items;
So if I have two items that have the same name, I save them to the "submap". For example, here I have:
map: {
key: beer map: {key: date: 1470783661 count: 50}
key: bread map {key: date: 1461538861 count: 0, key: date: 1461970861 count: 80}
}
How can I delete in this submap?
For example, if the key (date) 1461538861 with count = 0 delete this record in the submap. But I want to keep key: date: 1461970861 count: 80
so i get
map: {
key: beer map: {key: date: 1470783661 count: 50}
key: bread map {key: date: 1461970861 count: 80}
}
If I want to delete on the base of the outer key, here: beer, so I will also delete the outer map
so i get
map: {
key: bread map {key: date: 1461970861 count: 80}
}
Maybe I'm at least a little understanding. Thank you for all the comments. Complet program https://onecompiler.com/cpp/3xzqq36xf
class CSupermarket
{
public:
CSupermarket();
CSupermarket& store(const string &name,const CDate &date,const int &cnt);
map<string, map<int, CItem, cmpByCnt>> m_Items;
};
CSupermarket& CSupermarket::store(const string &name,const CDate &date,const int &cnt)
{
CItem a(name, date, cnt);
auto itr = m_Items.find(name);
if ( itr != m_Items.end())
itr->second.emplace(a.m_Date.m_Time, a);
else
m_Items.emplace(name, std::map<int, CItem, cmpByCnt>{{a.m_Date.m_Time, a}});
return *this;
}
int main()
{
CSupermarket s;
s . store ( "bread", CDate ( 2016, 4, 30 ), 100 )
. store ( "butter", CDate ( 2016, 5, 10 ), 10 )
. store ( "beer", CDate ( 2016, 8, 10 ), 50 )
. store ( "bread", CDate ( 2016, 4, 25 ), 100 )
. store ( "okey", CDate ( 2016, 7, 18 ), 5 );
// print
for(auto itr = s.m_Items.begin(); itr != s.m_Items.end(); ++itr)
{
cout << itr->first << " ";
for(auto i = itr->second.begin(); i != itr->second.end(); ++i)
{
cout << " date: " << i->first << " count: " << i->second.m_Cnt;
}
cout << endl;
}
}
| Deleting an element from a 2d map is almost the same as deleting it from a 1d map. You just want to call .erase on the inner map.
Say if you have a 1d map:
std::map<int, std::string> m = {
{1, "one" }, {2, "two" }, {3, "three"},
{4, "four"}, {5, "five"}, {6, "six" }
};
To delete {3, "three"}, you just do:
m.erase(3);
Now if you have a 2d map:
std::map<int, std::map<std::string, std::string>> m = {
{1, {{"en", "one"}, {"es", "uno"}}},
{2, {{"en", "two"}, {"es", "dos"}}},
{3, {{"en", "three"}, {"es", "tres"}}},
{4, {{"en", "four"}, {"es", "cuatro"}}},
};
To access the inner map, you would do:
m[1];
Now, if you want to remove {"en", "one"} from it, you just do:
m[1].erase("en");
And if you want to remove one of the entire inner map, you would do:
m.erase(3);
Demo: https://godbolt.org/z/aqzGTfc37
One thing to note is that deleting all elements of an inner map will not automatically delete that inner map from the outer map. To remove all the empty inner maps, you can do:
std::erase_if(m, [](auto& item){
auto& [number, inner_map] = item;
return inner_map.size() == 0;
});
Demo: https://godbolt.org/z/hMhMd8Y7b
For C++17 and earlier, there isn't erase_if function for map, so instead, you would do something like:
for(auto it = m.begin(); it != m.end();)
{
if(it->second.size() == 0)
{
it = m.erase(it);
}
else ++it;
}
Demo: https://godbolt.org/z/aTvPGGT8K
|
71,947,828 | 71,947,897 | Calling overridden methods from a vector of superclass pointers | I am currently writing a small game in OpenGL using C++. Coming from a non-C++ background, I have a simple question about overriding methods and how to call them using a pointer of a superclass type.
This is the case: I have a class Polygon containing the method void draw(). This class has two children called Rectangle and Circle, which both override the drawing method, as I am using different OpenGL calls depending on the type of polygon being drawn.
Now consider this: I wish to store all polygons (including both rectangles and circles) in an std::vector<Polygon*>. This is perfectly fine. However, iterating through the vector and calling draw automatically resorts to the superclass' version of the method.
How can I make a vector of type superclass-pointer, store pointers to subclass objects in it, and call overridden functions depending on the actual type of the object being used?
| You are describing polymorphism (or a lack thereof in your current implementation).
To make your draw function polymorphic, you must declare it virtual. See below for an example:
class Polygon {
public:
virtual ~Polygon() {}
virtual void draw() = 0;
};
class Rectangle : public Polygon
{
public:
void draw() override { std::cout << "Rectangle::draw()\n"; }
};
class Circle : public Polygon
{
public:
void draw() override { std::cout << "Circle::draw()\n"; }
};
Note three extra things in the above:
I also declared the destructor virtual. This allows for proper destruction of an object through its base class pointer.
I declared the base draw method as pure-virtual (the = 0 part). This means the Polygon class is abstract and cannot itself be instantiated. You may not want that, but to me it seems there's no use for a draw method on a base class anyway. Define one if you want. Up to you.
The override specifier is optional, but recommended (language feature introduced by C++11). It instructs the compiler that you're intentionally overriding a virtual method, and so if no such method exists to be overridden then it will generate a compiler error.
|
71,948,111 | 71,957,081 | Why does a function called inside a inline function not require definition? | Consider the following example:
extern void not_defined();
void f() {
not_defined();
}
int main() {}
If I were to compile and link the above program, I get a linker error undefined reference to not_defined(). (https://godbolt.org/z/jPzscK7ja)
This is expected because I am ODR using not_defined.
However, if I make f() a inline function, the program compiles and links correctly (https://godbolt.org/z/qEEob9ann):
extern void not_defined();
// inline is added here
inline void f() {
not_defined();
}
int main() {}
This also works for inline definitions of member functions (since they are also inline?) (https://godbolt.org/z/xce3neofW):
extern void not_defined();
struct C {
void f_member() {
not_defined();
}
void recurse() {
f_member();
};
};
inline void f_free_inline() {
not_defined();
}
// void f_free() {
// not_defined();
// }
int main() {
C c;
// f_free_inline();
}
If I were to uncomment f_free or f_free_inline() in main() it no longer works . This effects seem to be even transitive, since recurse calls f_member, and f_member calls not_defined().
So my questions is, what's special about inline functions that makes this possible?
EDIT:
This trick cease to work if the inline function is inside the purview of a module (even if it is not exported):
export module mod_interface;
extern void not_defined();
export inline void f_module() {
not_defined();
}
The above would result in a linker error for not_defined.
This is sad because I am porting a library to modules and suddenly got a lot of undefined references. Some of those functions in it were wrapped inside inline functions.
| Standard is not only a set requirements for compiler behaviour. It's also a set of requirements to programmer's behaviour.
GCC's linker wouldn't complain if a function X() that ODR-used a missing symbol Y is inline or static function, as there is no possibility that they would be called from outside module if it has local linkage and negligible, if it was inline.
But lo! Disregard the fact that you're able to compile and run this program, your program is ill-formed according to standard. Only in case of inline function X() linker would optimize it out as soon as it didn't found a reference to inline X() in any of compile units.
If it's not inline function, it would stay until final stage of linking and the missing name will be looked up through modules. Implementation of your compiler is such that it would be searched for before excluding unused X(). Some other compiler may behave differently.
That's why it's "ill-formed" code, but "no diagnostic required". Diagnostic is possible with certain implementations. Some implementations will diagnose both cases as an error and some are unable to detect your deception. Some implementations will detect the problem only if you had more than one compile unit.
|
71,948,304 | 71,948,382 | Undefined reference to studentType::studentType() | I'm trying to learn how to use class in cpp, and one of the activities had me make a class header and a separate cpp file for implementation.
here are my codes:
main.cpp
#include <iostream>
#include <string>
#include "studentType.h"
using namespace std;
int main()
{
studentType student;
studentType newStudent("Brain", "Johnson", '*', 85, 95, 3.89);
student.print();
cout << "***************" << endl << endl;
newStudent.print();
cout << "***************" << endl << endl;
return 0;
}
studentType.h
#ifndef CODINGPROJECTS_STUDENTTYPE_H
#define CODINGPROJECTS_STUDENTTYPE_H
#include <string>
using namespace std;
class studentType {
private:
string firstName;
string lastName;
char courseGrade;
int testScore;
int programmingScore;
double GPA;
public:
//GETTERS
string getfirstName() const;
string getlastName() const;
char getcourseGrade() const;
int gettestScore() const;
int getprogrammingScore() const;
double getGPA() const;
//SETTERS
void setfirstName(string name);
void setlastName(string name);
void setcourseGrade(char course);
void settestScore(int test);
void setprogrammingScore(int programming);
void setGPA(double gpa);
studentType(string first, string last, char course, int test, int programming, double gpa);
studentType();
void print();
};
#endif
studentTypeImp.cpp
#include <iostream>
#include "studentType.h"
using namespace std;
studentType::studentType(string first, string last, char course, int test, int programming, double gpa){
}
void studentType::setfirstName(string first){
firstName = first;
}
void studentType::setlastName(string last){
lastName = last;
}void studentType::setcourseGrade(char course) {
courseGrade = course;
}
void studentType::settestScore(int test) {
testScore = test;
}
void studentType::setprogrammingScore(int programming){
programmingScore = programming;
}
void studentType::setGPA(double gpa){
GPA = gpa;
}
string studentType::getfirstName() const{ return firstName;}
string studentType::getlastName() const{ return lastName;}
char studentType::getcourseGrade() const{return courseGrade;}
int studentType::gettestScore() const{ return testScore;}
int studentType::getprogrammingScore() const{ return programmingScore;}
double studentType::getGPA() const{return GPA; }
void studentType::print(){
cout << "Name: " << getfirstName() << " " << getlastName() << endl;
cout << "Grade: " << getcourseGrade() << endl;
cout << "Test Score: " << gettestScore() << endl;
cout << "Programming Score: " << getprogrammingScore() << endl;
cout << "GPA: " << getGPA() << endl;
}
I have an inkling that it has to do with my header file but I don't know where to start.
| Add a definition for that default constructor which you declared in the header file. One way to do this is to add this code to studentTypeImp.cpp:
studentType::studentType() {
}
|
71,948,320 | 71,948,503 | Check each member of a template parameter pack for equality | So, I already have a workable solution, but i want to know if there is any other way to handle this, in case i'm missing something obvious and simple.
What i want to express
if((a==c)||...)
where c is a parameter pack and a is a variable. Basically I want it expanded to
if( (a == c1) || (a == c2) ... etc)
As a MRE
template <typename A, typename... C>
void foo(A a, C... c) const
{
if((a == c)||...)
return;
}
The solution i ended up going with was
if (
[](auto a, auto c1, auto c2)
{
return a.value == c1 || a.value == c2;
}(a, c...))
|
What i want to express
if((a==c)||...)
where c is a parameter pack and a is a variable. Basically I want it
expanded to
if( (a == c1) || (a == c2) ... etc)
C++17 fold expression should be enough, which will expand what you expect
template <typename A, typename... C>
void foo(A a, C... c)
{
if(((a == c)|| ...))
return;
}
Demo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.