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:... | 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_... |
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 ... | 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 us... |
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... | 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 st... | 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 t... |
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 th... | 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 ope... |
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 dire... |
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= "abcdefghijklmnopqrstuvw... | 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 c... |
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 director... | 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 <... | 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. Wh... |
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::thr... | 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 necess... |
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 prev... | 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, readin... |
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 : pub... | 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];
... |
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]... |
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... | [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... |
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> {
... | 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 ca... |
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 ... | 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 funct... |
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:
... | 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 fi... |
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 (sourc... | 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 M... |
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... |
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 ... |
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);... | 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]);
... | 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 p... |
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;
sr... | 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 mai... |
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... | 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... |
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 u... | 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,... |
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 <iostr... | 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... |
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) {}
... |
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 fundamental... |
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 s... |
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 t... | 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... | 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 simi... |
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 ... | 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 "
<< "a... |
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 ... | 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 line... |
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... | 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 ... |
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 cla... | 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... | 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. ... | 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... |
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 ... | 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, bu... |
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 o... |
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. Th... |
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;... | 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 ... |
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 f... | 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) documen... | 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", "workforc... |
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 ju... |
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 o... | 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... |
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... | 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 ou... |
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> <ident... |
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... | 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:... |
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 missi... | 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& ... |
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 operat... | 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 ... |
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 b... | 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-... |
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)
S... | 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... | 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 ... |
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;
... | 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 de... |
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";
... |
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 ca... |
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 ... | 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 develop... |
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
... | 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 ... |
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 file... | 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 ... | 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 gen... |
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 executab... | 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 ... |
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... | 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-cla... |
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* ... | 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 a... |
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... | 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 v... |
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... | 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 Std... |
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 <-- namesp... |
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{}); // pri... |
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_... | 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 requi... |
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?
str... | 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>>* ... |
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... | 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... |
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 ... |
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()
...
_, er... | 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 eas... |
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 approac... | 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.
... |
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... | 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: err... | 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-in... |
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 $jumboFramesL... |
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 i... | 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 gener... |
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 s... | 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 d... |
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 e... | 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 ... |
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;
};
tem... | 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... |
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[])
{
... | 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;
BOO... |
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 t... | 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,-... |
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];
... | 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 tem... |
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>, ... | 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>, ... |
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... | 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 ... | 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 be... |
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)... |
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 appro... |
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 y... | 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(... |
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++, h... | 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, ... |
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... | 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 th... |
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() {
... | 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... |
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>{ {it... |
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... | 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 sy... |
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:... | 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... |
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 v... |
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... |
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() {
}
... | 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 Develo... |
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 hav... | 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?... | 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" ) == s... |
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 require... | 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... |
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: 1461... | 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.e... |
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... | 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()... |
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 mak... | 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 lo... |
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 newStuden... | 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
... |
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)|| .... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.