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 |
|---|---|---|---|---|
70,382,263 | 70,382,486 | Conjunction of concepts before auto? | I'm learning C++20 concepts. Is there a way to do a conjunction of concepts in-place before an auto? For example, If I have a MutableGraph<G> concept and a VertexListGraph<G> concept, I could define
template <typename G>
concept MutableVertexListGraph = MutableGraph<G> && VertexListGraph<G>;
and do
MutableVertexListGr... | No, there is no way to combine concepts when applying constraints to a deduced variable definition's type.
ConceptName auto variable = ...; is fairly readable. The ConceptName is probably pretty self-explanatory, and it leaves plenty of room for the variable definition.
Concept1 && Concept2 && Concept3 auto variable = ... |
70,383,288 | 70,456,840 | How is optional assignment constexpr in C++ 20? | To the internal content of an optional, doesn't the optional require placement new in order to reconstruct the internal in place storage or union? Is there some new feature like placement new in C++ 20 that allows for constexpr assignment of std::optional?
template< class U = T >
optional& operator=( U&& value );
(sinc... |
To the internal content of an optional, doesn't the optional require placement new in order to reconstruct the internal in place storage or union?
For assignment, yes it does.
But while we still cannot do actual placement new during constexpr time, we did get a workaround for its absence: std::construct_at (from P078... |
70,383,755 | 70,390,174 | How to save triangulation object(Constrained_Delaunay_triangulation_2) to file(vtk, vtu, msh etc) in CGAL | Created simple program based on 8.3 Example: a Constrained Delaunay Triangulation. And just wanna to export it to some common mesh file format like vtk, msh etc, to be able open it in GMesh or ParaView. To do so I found that most straightforward way is to use write_VTU. And at the beginning and at the end of example co... | As documented here the face type of the triangulation must be a model of DelaunayMeshFaceBase_2. You can for example use Delaunay_mesh_face_base_2 like in this example.
|
70,384,034 | 70,384,271 | Override parameter pack declaration and expansion loci | I have a simple interface setter:
template<typename Interface>
struct FrontEnd
{
virtual void inject(Interface*& ptr, Client* client) = 0;
}
I want to implement these interfaces through parameter packs like this:
template<typename ... Is>
struct BackEnd : public FrontEnd<Is>...
{
void inject(Is*& ptr, Client* cli... | You probably want something like this
template<typename Is>
struct OneBackEnd : public FrontEnd<Is>
{
void inject(Is*& ptr, Client* client) override { /* whatever */ }
};
template<typename .... |
70,384,319 | 70,386,903 | Define boost variant type to pass explicitly empty values | I want to have boost::variant with empty state. So I define a boost::variant with boost::blank as the first alternative. But then I want to pass this as function parameter:
void f(Variant v);
...
void g()
{
f(boost::blank{});
}
It does not look nice due to braces. Seem to be better if it accepted boost::none:
void ... | You can just default construct, which will initialize the first element type.
Alternatively you can define your own constant of type boost::blank:
Live On Wandbox
#include <boost/variant.hpp>
#include <iostream>
using Variant = boost::variant<
boost::blank,
int,
std::string>;
void foo(Variant v = {}) {
... |
70,384,353 | 70,385,637 | How to assign N tasks to M threads max.? | Im new to C++, and trying to get my head around multithreading. I’ve got the basics covered. Now imagine this situation:
I have, say, N tasks that I want to have completed ASAP. That‘s easy, just start N threads and lean back. But I’m not sure if this will work for N=200 or more.
So I’d like to say: I have N tasks, and... |
I have N tasks, and I want to start a limited number of M worker threads.
How do I schedule a task to be issued to a new thread once
one of the previous threads has finished?
Set your thread pool size, M, taking into account the number of threads available in your system (hardware_concurrency).
Use a counting_sema... |
70,384,919 | 70,385,299 | Parsing does not work: terminate called after throwing an instance of "std::invalid argument" | I want to have a function which returns a vector of 2 integers. The input is a string.
The layout of the string that is inserted should always be like this: "COORDINATES 123 456" with the coordinates being integers of any length.
If the string is "COORDINATES 123" or "COORDINATES 123 456 789", the function should retur... | #include <iostream>
#include <string>
#include <vector>
std::vector<int> getCoordinates(std::string string){
auto count = 0;
std::string coordinates;
int coordinatesInt;
std::vector<int> vector;
for(unsigned i = 0; i < string.size(); i++){
if(string.at(i) == ' '){
count++;
unsigned j = 1;
w... |
70,385,287 | 74,393,300 | CMake boost_python not found | Hi I'm having some problems with using cmake to build this example. This is what I have:
├── _build
│ ├── CMakeCache.txt
│ ├── CMakeFiles
│ ├── cmake_install.cmake
│ └── Makefile
├── CMakeLists.txt
├── hello_ext.cpp
└── README.md
CMakeLists.txt:
cmake_minimum_required(VERSION 3.16.3)
project(test)
# Find py... | As Tsyvarev posted in the comments I just had to removed the config file in /usr/local/lib/cmake/Boost-1.77.0/BoostConfig.cmake and rebuild my project.
|
70,385,806 | 70,385,866 | How fix this : error: no member named 'setBackgroundColor' in 'QTableWidgetItem'? | ui -> tablica -> item(i, j) -> text().toInt(&f1);
if(f1)
{
ui -> tablica -> item(i, j) -> setBackgroundColor(Qt::white);
}
Error with method setBackgroundColor.
| Use: void QTableWidgetItem::setBackground(const QBrush &brush)
See here why:
https://doc.qt.io/qt-5/qtablewidgetitem-obsolete.html#setBackgroundColor
void QTableWidgetItem::setBackgroundColor(const QColor &color)
This function is obsolete. It is provided to keep old source code working. We strongly advise against usin... |
70,385,996 | 70,386,402 | How to update comboBox items when the database is being changed? | I fill the comboBox with items from database. When I try to add new item, erasing all items and adding them again, if db is being changed, I see these errors:
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
QSqlDatabasePrivate::addDatabase: duplicate conn... | If you call foodListConstructor() multiple times, you are going to be calling addDatabase() multiple times. Which is perfectly fine, per the documentation:
Adds a database to the list of database connections using the driver type and the connection name connectionName. If there already exists a database connection ca... |
70,386,101 | 70,386,256 | Thread pool not completing all tasks | I have asked a simpler version of this question before and got the correct answer: Thread pools not working with large number of tasks
Now I am trying to run tasks from an object of a class in parallel using a thread pool. My task is simple and only prints a number for that instance of class. I am expecting numbers 0->... | There's too much code to analyse all of it but you take a pointer by reference here:
{
test* myTest = new test(i);
std::function<void()> myFunction = [&] {myTest->task(); };
pool.submit(myFunction);
} // pointer goes out of scope
After that pointer has gone out of scope you will have undefined behavior if ... |
70,386,516 | 70,386,661 | Exception in constructor initialization list | Lets say I have the following code
class B
{ /* implementation*/ };
class A
{
B b;
char * c;
A() : b(), c(new char[1024])
{}
~A()
{
delete[] c;
}
};
int main()
{
A* a = nullptr;
try
{
a = new A();
}
catch(...)
{
}
}
I want to... |
I want to understand what will happen if c(new char[1024]) will throw exception? Will b correctly destroyed?
Yes. When a constructor throws, any already-constructed members and base classes are destructed automatically.
Can caller catch this exception?
Yes.
If yes, what will be the value of a?
nullptr, because t... |
70,387,136 | 70,387,307 | Iterating over first n elements of a container - std::span vs views::take vs ranges::subrange | So with c++ 20 we get a lot of new features with ranges, spans and so on. Now if i need to iterate over a container, but only the first n elements, what would be the most appropriate way and is there any practical difference going on behind the scenes? Or is it perhaps a better idea to just go back to regular for loops... |
views::take is the most generic, it is suitable for almost any range, such as input_range, output_range, and more refined ranges.
std::span only applies to contiguous_range.
Although ranges::subrange is also generic, but since you need to obtain the bound of iterator through elements.begin() + n, this requires that ... |
70,387,151 | 70,745,139 | Fully embedding python into Qt application | I am looking for a way of fully embedding python into a Qt application. With this, I mean that I want to build a Qt application that executes python code and I can fully distribute without having to care about which python version is installed in the target machine, or without having to ask the future user to install p... | I finally found a workaround.
I executed the python interpreter from terminal, and printed sys.path, showing the correct paths.
Then, in C++, I appended the correct paths to sys.path, removing the wrong ones.
|
70,387,327 | 70,387,486 | cout operator << doesn't work for vector<char> | Why doesn't this vector print out?
void str_read(std::vector<char> str);
int main() {
std::vector<char> str;
str_read(str);
std::cout << str << std::endl;
return -1;
}
void str_read(std::vector<char> str) {
while (1) {
char ch;
scanf("%c", &ch);
if (ch == '\n')... | You get the error because there is no standard operator<< defined for std::vector. If you want that, you have to implement it yourself.
Even so, str_read() takes in a std::vector by value, so it receives a copy of the caller's vector, and thus any modifications it makes will be to that copy and thus lost when str_read... |
70,387,840 | 70,477,519 | Does something wrong with Widget&& var1 = someWidget;? | recently, i began to learing something about universal reference https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers and it says that Widget&& var1 = someWidget; //here, "&&" means rvalue reference. i know that "&&" can be universal reference or rvalue reference,but i thought somewidget must be a l... | I found that blog post to be confusing. I'd recommend reading a good chapter in a book or the standard itself instead of that post. Part of the problem is that the blog post is 10 years old, so people were still thinking about the new features and how to teach them. I don't think that code even compiles though. I teste... |
70,387,878 | 70,400,473 | Does using sigwait and signalfd concurrently in a multithreaded program result in a race condition? | I am writing a multi-threaded program where, among other things, I have a thread listening to a socket for incoming network connections. To allow this to be interrupted, I am using poll in combination with signalfd (rather than a raw await call). However, I also have other threads that I need to be able to notify of po... | I have looked into the linux source code, and have come up with an answer to my own question: there is no race condition, as the signalfd watchers are explicitly notified before the signal is sent, so they will always be notified before the signal is sent (and caught). Specifically, in linux/kernel/signal.c, we see:
ou... |
70,387,906 | 70,388,124 | How and when does the mem size of a parameter in a function, in c++, will be a concern? | Recently I received a feedback on a issue with the following warning from a colleague, who uses Coverity, a static analysis tool.
Passing the value of a large parameter (PASS_BY_VALUE)
pass_by_value: Passing parameter parameter_name of type class_name (size 184 bytes) by value, which exceeds the low threshold of 128 P... |
Pass by value
Pass by reference
Advantage
cost of passing the argument
copy object
copy pointer
by value, if sizeof(T) <= sizeof(T*),by ref, if sizeof(T) > sizeof(T*)
object access
direct
indirect
by value
can alias
no the optimizer can do more access optimizations
yesoptimizer is restricted in access opti... |
70,387,962 | 70,387,994 | Does declaring a constructor '= default' in a header file break the ODR | If I define the destructor (or any autogenerated constructor) as default like this:
struct A {
~A() = default;
};
And then include this in several translation units, does this break the ODR? Can someone walk me through the steps at on the ODR page? Because i am struggling to understand if the compiler generated de... | No ODR violation. Member functions are implicitly inline if they are defined, defaulted or deleted inside a class definition.
https://en.cppreference.com/w/cpp/language/inline
The implicitly-generated member functions and any member function
declared as defaulted on its first declaration are inline just like
any other... |
70,388,077 | 70,388,217 | Working with std::unique_ptr and std::queue | Maybe it's my sinuses and that I fact that I just started learning about smart pointers today I'm trying to do the following:
Push to the queue
Get the element in the front
Pop the element (I think it will automatically deque once the address out of scope)
Here is the error
main.cpp:50:25: error: cannot convert ‘std:... | If I got your aim correctly, you definitely want
std::unique_ptr<MyObject::Packet> MyObject::FrontOfQueue()
{
auto rv = std::move(PacketQueue.front());
PacketQueue.pop();
return rv;
}
// ...
std::unique_ptr<MyObject::Packet> frame = object.FrontOfQueue();
Notice, no raw pointers are used.
I think it will autom... |
70,388,341 | 70,388,386 | Why am I unable to use a variable when using the map() function? | int main()
{
unsigned int num = 2;
string map[num][3] = {{"c","d","s"}, {"A", "u", "p"}};
for(int y = 0; y < 2; y++)
{
for(int x = 0; x < 3; x++)
{
cout << map[y][x];
}
cout << endl;
}
}
I'm using X... |
You can declare an array only with constant size, which can be deduced
at compile time.
source: variable-sized object may not be initialized c++
SO, change the line:
unsigned int num = 2;
to this:
unsigned const num = 2;
|
70,388,370 | 70,391,110 | How to make the conversion from 'int' to 'char' reasonable under -Werror=conversion option? c++11 | error: conversion from ‘int’ to ‘char’ may change value [-Werror=conversion]
build cmd example:
g++ -std=c++11 test.cpp -o a.out -Werror=conversion
auto index = 3;
char singleChar = 'A' + index; // I want to get A-Z
I hope sigleChar is dynamically assigned.
could you pls help me to solve this error report with... | 'A' + index; // I want to get A-Z would only works for ASCII, not EBCDIC for example.
A more portable solution (and not int to char conversion involved) is array indexing:
char singleChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index];
|
70,388,536 | 70,395,182 | Boost.Asio async_read a string from a socket | I'm trying to write a function async_read_string_n to asynchronously read a string of exactly n bytes from a socket with Boost.Asio 1.78 (and GCC 11.2).
This is how I want to use the function async_read_string_n:
void run() {
co_spawn (io_context_, [&]() -> awaitable<void> {
auto executor = io_context_.get_execut... | You don't have to use streambuf. Regardless, using the >> extraction will not reliably extract the string (whitespace stops the input).
The bigger problem is that you have to choose whether you want to use
co_await (which requires another kind of signature as your second link correctly shows)
or the async result proto... |
70,388,731 | 70,389,273 | How to Use std::any as mapped_type | I am trying to solve the problem asked yesterday on SO based on this answer.
I have modified the code given here to use std::any instead of void*. The code that i currently have is as follows:
#include <iostream>
#include <map>
#include <vector>
#include <any>
#include <typeindex>
struct cStreet{};
struct cHouse{};
str... | Based on this answer, redefine your myMap as:
std::map<std::type_index, std::any> myMap{
{typeid(cStreet*), std::ref(m_Properties.Streets)},
{typeid(cHouse*), std::ref(m_Properties.Houses)},
{typeid(cComputer*), std::ref(m_Properties.Computers)},
{typeid(cBook*), std::ref(m_Properties.Book)}
};
Then cast an... |
70,389,159 | 70,389,578 | How to convert GL_RED to GL_RGBA format | This is the code for the fragment shader.
in vec2 TexCoord;
uniform sampler2D texture1;
out vec4 OutColor;
void main()
{
OutColor = texture( texture1 , TexCoord);
}
Whenever any GL_RED format texture is passed the greyscale image outputs as red in color.
I can fix that by using the red parameter of the textur... | Set the texture swizzle parameters with glTexParameter. e.g.:
glBindTexture(GL_TEXTURE_2D, textureObject);
if (channels == 1)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL... |
70,389,233 | 70,395,552 | Changing the center of a gaussian using FFTW in C++ | For a project I need to propagate a gaussian in real space using the Fourier transform of a gaussian centered at the origin using
What I want to calculate
Here is the latex code, since I can't include images yet
N(x | \mu, \sigma) = F^{-1}{F{ N(x |0, \sigma)} e^{-i\ 2\pi \mu\omega} \right},
where \omega is the frequenc... | Generally, the more obvious is the mistake, the more time it takes to find it.
This was verified here.
The mistake is simply here:
z[1] = out[i][0]*std::sin(w) + out[i][0]*std::cos(w);
It should be:
z[1] = out[i][0]*std::sin(w) + out[i][1]*std::cos(w);
Besides, I don't know why you didn't use N__ft = N, but I guess i... |
70,389,604 | 70,564,531 | Bitmap fonts not rendering correctly for some characters | I am generating the bitmap font texture from here - https://snowb.org/
The font for "Name - wxyz" is rendering as below -
The code is very much similar to the one posted for this question - Bitmap font rendering issue, so I will only post my code for the quad and texture coordinate calculation for the characters (I am... | The thing that worked for me with the code I have added to the question was to modify the y vertex coordinate as such
float ycoordBegin = beginOffsetY - texData[i].height - texData[i].yOffset;
float ycoordEnd = beginOffsetY - texData[i].yOffset;
With this modification the text appears correctly as below -
... |
70,389,630 | 70,389,631 | "LNK1104: cannot open file mclmcrrtd.lib" Error in Qt Creator | I generated *.dll dynamic-link library file by compiling the application I developed in MATLAB using MRC (MATLAB Runtime Compiler). I'm using the MSVC compiler and qmake toolset in the Qt Creator environment to distribute and/or use the procedures in the application I developed in MATLAB in the Windows OS environment. ... | 1. Definition of Error
I tested this bug by starting a similar project. When I compile the project in Qt Creator I got the following error:
LNK1104: cannot open file 'mclmcrrtd.lib'
2. Steps To Fix The Error
Follow the steps below to fix the problem:
I didn't add dependencies manually in QT Creator. I added a dynami... |
70,389,922 | 70,390,793 | Content of class method determined by the template value | By using c++ 14 or c++11, do we have an elegant approach to do the following task? Number of members and type of operations are determined by the template input value 'count'
template<int count>
class show{
public:
run(){
if (count == 1){
int x;
} else if(coun... | Yes, you can use specialization:
template<int count>
class show;
template<>
class show<1>{
int x;
public:
show(int _x):x{_x}{}
void run(){
std::cout << "val of x " << x << std::endl;
}
};
template<>
class show<2>{
int x,y;
public:
show(int _x, int _y):x{_x}, y{_y}{}
vo... |
70,389,931 | 70,395,999 | Using OpenDDS with Qt6 | Can someone guide me on how to use OpenDDS with Qt6? I need to make a Chatroom application on Qt with the help of OpenDDS and I can't find any learning material for that.
| OpenDDS has a demo used to demonstrate interoperability with other DDS implementations that uses Qt that could serve as an example. It's Qt 5 though, we haven't updated it to Qt 6 yet. There's also some more information about OpenDDS and Qt listed here.
|
70,390,677 | 70,391,192 | Adding Decimal Numbers | Adding decimal numbers were my exam question.
Our teacher said the right code is this (Look below), but it doesn't work what's the problem
This is the question: 9/10-11/12+13/14-15/16+....49/50 Write a c++ program to calculate this question
Here is the code:
#include <iostream>
using namespace std;
int main()
{
do... | First of all, your code's first bug is that in the for-loop, you have typed x + 2.0 which is not an assignment statement. So it really doesn't add 2 to the value of x. Instead, you have to write x += 2.0. And the second bug is that you have to place p = -p; inside the loop. Otherwise, it won't have any effects.
Now by ... |
70,390,882 | 70,391,022 | is_trivially_copyable behaves differently between the constructor I implemented and the default | There is a demonstrative code for std::is_trivially_copyable
https://en.cppreference.com/w/cpp/types/is_trivially_copyable
void test()
{
struct A {
int m;
A(const A& o):m(o.m){}
};
struct D {
int m;
D(D const&) = default; // -> trivially copyable
D(int x) : m(x + 1)... | This is how it is defined in c++:
https://en.cppreference.com/w/cpp/language/copy_constructor#Trivial_copy_constructor
Trivial copy constructor
The copy constructor for class T is trivial if all of the following are true:
it is not user-provided (that is, it is implicitly-defined or
defaulted) ;
T has no virtual membe... |
70,391,370 | 70,391,958 | How to read from multiple lines in a file? | I am learning C++ and am having a bit of a hard time with files. This is a little exercise that I am trying to do. The program is meant to read from a file and set it to its proper variables. The text file is as so:
Adara Starr 94
David Starr 91
Sophia Starr 94
Maria Starr 91
Danielle... | I hope this helps:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
const int MAXNAME = 20;
int main() {
ifstream inData("input.txt");
string str = "";
while (!inData.eof()) {//use eof=END OF FILE
//getline(inData, str); use to take the hole row
/*can use string... |
70,392,385 | 70,392,576 | Having trouble printing a series | Here's the problem statement for what I'm supposed to do:
Write a program to print the following series up to the term input by user.
0, 1, 1, 2, 3, 5, 8, 13, ….
Where 0 is 1st term and 13 is 8th term.
Hint: 0, 1
0+1 = 1
0, 1, 1
1+1 = 2
0, 1, 1, 2
And here's my code:
int prev_i = 0;
cout << "Enter a number: " <... | You're trying to generate a fibonacci sequence (starts with two terms (0,1), and each subsequent term is the addition of the prior two). Therefore, i should not be part of the calculation; it is only there to control looping.
A simple generation of the first ten numbers in the sequence is simply this:
#include <stdio.h... |
70,392,665 | 70,392,751 | Why can't I access a std::vector<std::pair<std::string, std::string>> through vec[i].first()? | I am attempting to print data from a std::vector<std::pair<std::string,std::string>> via a for loop. MSVC says that I can't call make a call through this vector. I tried it with std::vector<std::pair<int, int>> as well and got the same error. I tried iterating with a for loop on a std::vector<int> and it worked fine. ... | Your std::pair is basically (in a manner of speaking):
struct std::pair {
std::string first;
std::string second;
};
That's what std::pairs are. first and second are ordinary class members, not methods/functions. Now you can easily see what's happening: .first() attempts to call first's () opera... |
70,393,722 | 70,394,102 | Can we use two different mutex when waiting on same conditional variable? | Consider below scenario:
Thread 1
mutexLk1_
gcondVar_.wait(mutexLk1);
Thread 2
mutexLk2_
gcondVar_.wait(mutexLk2);
Thread 3
condVar_
gcondVar_.notify_all();
What I observe is that notify_all() does not wake up both the threads but just one on the two. If i were to replace mutexLk2 with mutexLk1. I get a functional c... | It seems you violate standad:
33.5.3 Class condition_variable [thread.condition.condvar]
void wait(unique_lock& lock);
Requires: lock.owns_lock() is true and lock.mutex() is locked by the
calling thread, and either
(9.1) — no other thread is waiting on this condition_variable object
or
(9.2) — lock.mutex() returns the... |
70,394,305 | 70,394,899 | Sort function is giving error in C++ code of merge sort | #include <iostream>
using namespace std;
// merging two sorted array
void merge1(int a[], int b[], int m, int n)
{
int c[m + n];
for (int i = 0; i < m; i++)
c[i] = a[i];
for (int i = 0; i < n; i++)
c[m + i] = b[i];
sort(c, c + m + n);
for (int i = 0; i < (m + n); i++)
cout << c[i] << " ";
}
int ... | The program works but on higher versions of clang and gcc, which implies a higher version of the standard being required. This problem can be reproduced if you drop the version of the compiler being used. If you drop the compiler version, you will need to include <algorithm> and the program will work fine.
Take a look.... |
70,394,783 | 70,394,837 | C++11 Check if at least one element in vector is not in another vector | I wrote the following code in order to check if at least one element in vector is not in another vector.
There are no duplicates in the vectors. Only unique elements
Is there a more elegant way to do it by using the stl?
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
#include <al... | It depends on your definition of "different", but:
bool areVectorsDifferent(const vector<int> &a, const vector<int> &b){
return a.size() != b.size()
|| std::set<int>{a.cbegin(), a.cend()} != std::set<int>{b.cbegin(), b.cend()};
}
|
70,394,812 | 70,394,940 | Sending user inputted commands to an arduino in c++ using system() on a linux terminal | Using a c++ program i can successfully send commands to an arduino. The code uses the command:
system("$echo [command] > dev/ttyACM0");
Currently i must manually input the commands into this space, I was wondering if it's possible for a user to input the command, and for it to then be added to the string within system(... | This is an approximation of what I think you want:
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::string command;
if(std::getline(std::cin, command)) { // read user input
std::ofstream ard("/dev/ttyACM0"); // open the device
if(ard) {
ard << command << '... |
70,395,502 | 70,396,041 | Erasing duplicates from two vectors using only iterators | How can I delete duplicates from two vectors of strings (delete them from both vectors) using only iterators?
I suppose it doesn't work because if values are already deleted they can't be compared, but I can not think of any other solution, only if I had one function to erase both elements at the same time.
void obrisi... | I can suggest the following approach. In the demonstration program below I am using vectors of the type std::vector<int> for simplicity.
#include <iostream>
#include <vector>
#include <iterator>
$include <algorithm>
int main()
{
std::vector<int> v1 = { 1, 2, 1, 2, 3, 4 }, v2 = { 1, 2, 3, 5 };
for (auto first ... |
70,395,538 | 70,395,648 | Illegal hardware instruction on a c program compiled on Mac | I am getting an illegal hardware instruction error when compiled on mac. Appreciate any pointers.
#include<iostream>
using namespace std;
int * fun(int * x)
{
return x;
}
int main()
{
int * x;
*x=10;
cout << fun(x);
return 0;
}
| Pointers are just pointers. In your code there is no integer that you could assign a value to.
This
int * x;
Declares x to be a pointer to int. It is uninitialized. It does not point anywhere. In the next line:
*x=10;
You are saying: Go to the memory that x points to and assign a 10 to that int. See the problem? Ther... |
70,396,126 | 70,409,760 | C++ How to set pixel colors | I created a code which change a certain pixels on the screen but when i want to change more pixels the performance of program will slow down.
You will see glitches and it's not that pretty as it should be.
Question:
How can i inprove performance of the code.
If I want to change more pixel or eventually all pixels on... | If I understand correctly, you are trying to draw outside a window.
Every time you SetPixel you send a WM_PAINT message, which repaints the whole window.
That dramatically slows down your program. What you should do is use GDI, GDI+ or Direct2D to create a bitmap or a rectangle to then draw it at once.
Drawing outside ... |
70,396,216 | 70,396,562 | Trying to understand cause of increased compile time going from C++11 to C++14 | Migrating from C++11 to C++14, I have a source file that usually compiles in ~20s in C++11 mode, but when compiling the same file in C++14 mode the compile time increase to ~340s. That's an increase of about 17 times. The size of the generated object code doubles.
So the clarify my question, I'm trying to understand ... | Seems like this is known bug in gcc but isn't getting much traction.
Did you try to switch over to clang++?
PS from comment: Removing the {} behind the storage{} and manually initializing works.
|
70,396,339 | 70,396,635 | Shortest path algorithm in graph for queries | I have a weighted undirected Graph. Its vertices are part of two sets - S and T. Firstly, the edges are entered. Then it's specified which vertices are part of the T set (the rest are part of the S set). Then q queries follow. For every query(consists of a source vertex), the program must print the shortest path betwee... | You can reverse all edges and find the shortest path from the set of T (run Dijkstra from all T vertices together) to some vertex S. And precalculate all distances to each S and answer to query in O(1).
|
70,396,570 | 70,398,951 | mismatched types 'std::chrono::_V2::steady_clock' and 'std::chrono::_V2::system_clock' | I'm trying to build my program in mingw64 (GCC v11.2). I have the following struct:
In a header file:
struct Timer
{
std::chrono::time_point< std::chrono::steady_clock > start;
std::chrono::time_point< std::chrono::steady_clock > end;
Timer( );
~Timer( );
};
In a source file:
util::Timer::Timer( )
: s... | Thanks to the information provided in the comments, I came up with the following solution:
In the header file:
struct Timer
{
std::chrono::time_point< std::chrono::steady_clock > start;
std::chrono::time_point< std::chrono::steady_clock > end;
Timer( );
~Timer( );
};
In the source file:
util::Timer::T... |
70,397,103 | 70,397,466 | unable to compile googletest in eclipse | I am trying to compile googletest (git clone https://github.com/google/googletest.git -b release-1.11.0) but keep getting 1000+ linker errors.
I am running windows 10, eclipse CDT (latest), mingw (latest) gcc. I created an eclipse c++ project (executable, empty project).
added include paths to:
googletest
googletest/i... | Ah, there is a file
googletest/src/gtest-all.cc
which includes all source files. so all source files are compiled twice, deleting this file solves my problem
|
70,397,158 | 70,397,495 | Whats the difference between reference to an array and array as a parameters in functions? | What is the difference between functions, which have reference to an array:
// reference to array
void f_(char (&t)[5]) {
auto t2 = t;
}
and simply array:
// just array
void f__(char t[5]) {
auto t2 = t;
}
as a parameters?
The calling code is:
char cArray[] = "TEST";
f_(cArray);
f__(cArray);
char (&rcArr)[5]... | You can specify a complete array type parameter as for example
void f( int ( &a )[N] );
and within the function you will know the number of elements in the passed array.
When the function is declared like
void f( int a[] );
then the compiler adjusts the function declaration like
void f( int *a );
and you are unable ... |
70,397,382 | 70,436,876 | Build asimple c++ static library of ios(for unity), but cannot find the .a file | As the title mentioned, using macos 12.
example.hpp
extern "C"{
int summation();
}
example.cpp
#include "example.hpp"
extern "C"{
int summation()
{
return 10;
}
}
Then I create an Xcode project->static lib, add example.hpp and example.cpp, configure the build phase to ios only. Click on build, the xcode tell... | Solution is very simple, I create a new project, add the example.hpp and example.cpp into the project, set build target to ios only, click build, then the .a file is generated, I don't know why this happen, maybe some manipulation ruin the settings.
|
70,397,537 | 70,397,749 | VSCode and C++: Slightly lost with this error | I use the sample helloworld program and get syntax errors that make no sense to me. The strange part is that the program runs just fine, but the red squiggles in the code bother me and I'd like to understand why those are happening.
Code
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int... | Did you configure your c++ VS Code extension?
For example:
{
"configurations": [
{
"name": "Mac",
"includePath": ["${workspaceFolder}/**"],
"defines": [],
"macFrameworkPath": [
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks"
],
"compilerP... |
70,398,439 | 70,398,495 | How do i fix invalid operands of type double in C++? | Trying to do a Lab for school, but i keep getting this same error over and over again, and I am not sure what exactly it means.
First, here is my Code:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
const double PI = acos(-1); // arccos(-1) produces the value pi
const double SEC_IN_DAY = ... | CubedSum is a function. So it seems you need to write
double HohmannTime(double r1, double r2){
return PI * sqrt((CubedSum( r1, r2 )/ 8.0 * MU);
}
instead of
double HohmannTime(double r1, double r2){
return PI * sqrt((CubedSum)/ 8.0 * MU);
}
where in this statement
return PI * sqrt((CubedSum)/ 8.0 * MU);
there... |
70,398,573 | 70,398,753 | C++20 format sys_time with milliseconds precision | I'm trying to write a time string with a millisecond precision in MSVC 19.11 with /stc:c++latest.
With this i get 7 digits accuracy, what i don't want.
auto now = std::chrono::system_clock::now();
std::cout << std::format("{0:%d.%m.%Y %H:%M:%S}", now);
I tried std::cout << std::format("{0:%d.%m.%Y %H:%M:%S.3}", now);... | auto now = std::chrono::floor<std::chrono::milliseconds>(std::chrono::system_clock::now());
std::cout << std::format("{0:%d.%m.%Y %H:%M:%S}", now);
or:
auto now = std::chrono::system_clock::now();
std::cout << std::format("{0:%d.%m.%Y %H:%M:%S}", std::chrono::floor<std::chrono::milliseconds>(now));
I.e. the precision... |
70,398,668 | 71,787,312 | Is there a way to generate a clang-format file from a C++ code? | Supposing I have a C++ code already written and I want to generate a clang-format file from it, in order to note all the format settings of my code in this file, is there a way of doing it?
| Clang-Format Detector allows to generate clang-format file for the selected files. It also has a very convenient feature of seeing the result and adjusting it. Won't work for entire codebase though.
|
70,398,835 | 70,408,423 | Access is denied - UWP full trust process | I have a UWP C++/WinRT app and a C++/WinRT console application.
The UWP app uses the FullTrustProcessLauncher to launch the console application, and the console application is supposed to launch an arbitrary .exe file on the system, e.g. cmd.exe.
The whole code of the console application is here:
#include "pch.h"
#in... | Not all Windows Runtime APIs are supported in the context of Win32
'classic' desktop apps as they are intended only for use in the "AppContainer" context of the Universal Windows Platform (UWP).
For a Win32 desktop application, the best solution is to use ShellExecuteEx. This function handles User Account Control (UAC)... |
70,399,226 | 70,577,833 | Linking C++ OpenCV to an app in Android Studio | I am integrating existing C++ code that uses OpenCV to an Android app, using Android studio. For this purpose, I have installed the package OpenCV-android-sdk and added it as a module to Android studio. I have also created a simple Kotlin app.
So far I have managed to integrate my C++ code into the project. After addin... | I finally managed. Here comes the recipe (validated under Windows).
Make sure to download the OpenCV Android SDK and copy it somewhere.
The project must be created as a Native C++ app (Phone and tablet). A cpp folder is automatically created with a native-lib.cpp source file and a CMakeLists.txt.
Add the following line... |
70,399,420 | 70,401,337 | Get enum key from unordered map by string value | I need a function that needs to check if the input (std::string) is unique and return its corresponding enum value.
I already have been able to implement this function with just a simple vector, which checks if the input is unique.
it should return enumE::HELLO.
I tried to adapt the code above for the vector to suit th... | Based on the description of your example, here is a quick implementation. Of course, the logic may not be entirely what you wrote, but I am sure you can tweak it.
Why would you iterate through the whole string if std::string has a std::string::find function which will find a substring for you?
Is it necessary to go th... |
70,399,504 | 70,399,581 | Unsure why code is repeating certain outputs | I am doing this for a lab at school, however, in my code i get the correct outputs, but for some reason my inputs are repeating themselves. I am unsure why they are doing this, and have tried editing my code in several different ways in order to fix the problem, but to no avail.
here is my original code:
#include <ios... | The problem is that your ConvertSecondsToDays function is inadvertently printing its result to stdout via:
cout << days;
That is intermingled with the real output done in main. Remove the cout call and you should be good.
|
70,399,536 | 70,399,694 | why std::function is not executed | I am using std::bind to create a std::function type and typedef it, but its instance would not execute. Following is my code:
void func(int a, const std::string& b)
{
std::cout << a << ", " << b << std::endl;
}
typedef std::function<void (int, const std::string&)> THE_FUNCTION;
THE_FUNCTION f = std::bind(func, 18,... | Change this:
typedef std::function<void (int, const std::string&)> THE_FUNCTION;
with:
typedef std::function<void ()> THE_FUNCTION;
and it will work.
L.E.: When you call bind, it means you have a function that "is very similar" with what you want, and fill the rest of the arguments that are not needed with some pro... |
70,400,005 | 70,501,376 | Visual Studio 2019 Freeglut (via nuget) - cannot open "Freeglut.lib" | I've been trying to create a GLUT-compatible Visual Studio 2019 project. Manually installing has caused some extremely complicated issues and breaks the project completely (even after uninstalling it) so I'm just trying to use the Nuget package. The .h files seem to be included correctly after this. However, any use of... | Resolved by using this method and then adding the line
#include <windows.h>
|
70,400,496 | 70,401,202 | Why does std::poisson_distribution hang when passed a very large mean? | For example, the following code hangs, using my setup with a recent version of g++ and GNU libraries:
#include <random>
#include <cstdio>
std::default_random_engine rng;
int main(){
std::poisson_distribution<long> mine(34387423874230847234.0);
std::printf("%ld\n", mine(rng));
}
Try it online
The description ... | We just discussed that libstdc++ normalizes the part of the probability distribution that fits in the output type (so the relative probabilities are correct) whereas libc++ clamps it (so that the mean is as correct as possible). The former approach has greatly increased expected runtime in the case where the parameter... |
70,400,598 | 70,400,647 | on the line Sort(arr,arr +n ) , how arr+n specifies end position here? | This code is about sorting an array :
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n);
cout << "\nArray after sorting using "
"default sort is : \n";
//Here I started pri... | For arrays, array name arr indicates iterator pointing to first element of array and +n would increment that iterator by n elements. In your case, the sort algorithm should take beginning iterator and iterator pointing to one beyond last element.
arr: beginning iterator
arr+n: ending iterator (one beyond last element)
... |
70,400,666 | 70,401,197 | Giving error for wrong return type in C++ | #include<iostream>
using namespace std;
void factor(int n)
{
if(n<=1)
return;
for(int i=2;i*i<=n;i++){
while(n%i==0){
printf(i);
n=n/i;
}
}
if(n>1)
{
return n;
}
}
int main(){
factor(10);
}
Error:
return-statement with a value, in function r... | The problem is that your function factor has a return type of void but it actually returns an int object.
To solve this, you should match the return type of the function factor with what you're actually returning from inside the function as shown below.
Secondly you should also take care of the situation when none of t... |
70,400,906 | 70,400,954 | Is performing indirection from a pointer acquired from converting an integer value definitely UB? | Consider this example
int main(){
std::intptr_t value = /* a special integer value */;
int* ptr = reinterpret_cast<int*>(value ); // #1
int v = *ptr; // #2
}
[expr.reinterpret.cast] p5 says
A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integ... | The standard has nothing more to say on it than what you quoted. The standard only guarantees the meaning of a integer-to-pointer cast if that integer value was taken from a pointer-to-integer cast. The meaning of all other integer-to-pointer conversions are implementation defined.
And that means everything about them ... |
70,401,270 | 70,401,302 | This Declaration has no store class -> encounter problem while using bool in classes cpp problem | i was working on a college Project and encountered this problem ->
When I declare the bool a and store value true/false in it, code runs fine
but while I only declare, and stores the value afterwards, like in code, it shows an error, can anyone explain why it is...?
#include <iostream>
class Design{
public:
vo... | You must use a constructor. Classes and functions are different.
class Login: public Student{
//bool a = true; Works fine
bool a;
Login() : a(true)
{
}
public:
void authenticate(){
}
};
|
70,401,301 | 70,401,339 | Conversion of Binary to Decimals | I am writing a c++ program where the program takes the t test cases as input and asks the binary input t times, and after that displays the output.
I tried to code but for 1st test case it displays right output in decimal format but for further test cases its not displaying correct output result.
#include<iostream>
#in... | You initialize i, dec outside the outer while loop. Initialize them to 0 inside the outer while loop and it works:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
int num, r, dec = 0, i = 0;
cin >> num;
while (num != ... |
70,401,391 | 70,401,635 | Create comparator for inserting triplets in min priority queue | I have made a triplet using a class with all members as integers. I want to insert the triplet in min priority queue using STL in C++. I heard that it can be done using a bool comparator function, but don't have any idea about how to use it with 3 elements.
Note: I don't want to use vector pairs for inserting 3 values ... | I don`t know why you did std::vector, std::greater but.
#include <queue>
#include <vector>
class triplet {
public:
int element;
int arrIndex;
int elementIndex;
constexpr bool operator>(const triplet& r)
{
return element > r.element;
}
};
int main()
{
std::priority_queue<triplet, st... |
70,401,545 | 70,406,698 | How to use fltk graphic library with visual studio (community) 2022 for C++ project on Windows 11 PC | I have tried downloading the files from the website
and try using it directing it but it needs to be compile or generated i guess.
I am new to learning C++ and fltk graphic library.
Thanks in advance
| Yes!!! I finally got it.
Step 1
I install vcpkg,
follow the instructions and integrate with visual studio.
Then I download fltk using vcpkg:
vcpkg install fltk.
Step 2
Finally in Visual Studio, Linker>>General>>Additional Library Directories : refer to the lib folder which vcpkg produced during installation.
And C/C... |
70,401,573 | 70,401,655 | Invalid Read Of size 8 when passing a string to a function | Im a second year CS student and Im attempting to make a hangman game for fun during my winter break. Ive implemented the beginning of a menu class here, and yes I know this is too much oop for a project of this scope but I intent to reuse all these classes.
Anyways valgrind is telling me an Invalid read of size 8 and i... | If you look at this line:
cout<<". return to "<<parent->getName();
You access the parent's name here;
But for MainMenu, parent is nullptr, therefore it's an invalid access!
The line needs to be made conditional on parent being different from nullptr.
|
70,402,079 | 70,402,579 | tag dispatch based on conditional_t over is_floating_point | I am getting a strange, Call to function 'Equals' that is neither visible in the template definition nor found by argument-dependent lookup, for a simple tag dispatch implementation.
template <typename T>
bool Equals(T lhs, T rhs){
return Equals(rhs, lhs, conditional_t<is_floating_point<T>::value, true_type, false... | When performing the tag dispatching, you are not instantiating the true_type. But more importantly, you need to change the order of your functions, the tagged functions need to be defined before the function that is performing the dispatching, eg:
template <typename T> // for floating
bool Equals(T lhs, T rhs, true_typ... |
70,402,092 | 70,402,289 | Error passing rapidjson::Value type to another function | I needed to pass a variable with rapidjson::Value type to another function with the following code:
#include "filereadstream.h"
#include "stringbuffer.h"
#include "rapidjson.h"
#include "document.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace rapidjson;
using namespace std;
static void pr... | The error says
rapidjson::GenericValue<Encoding, Allocator>::GenericValue(const
rapidjson::GenericValue<Encoding, Allocator> &rhs) (...) is
inaccessible
That looks like a copy constructor to me. If the error is thrown at processJsonValue(testMember), try making your processJsonValue function take parameters by refere... |
70,402,420 | 70,402,475 | Is it safe to reassign *this inside a class' method? | I have an object that is related to some file stored on the disk. The object's constructor accepts this file as an argument, reads it and creates an actual object with the settings depending on the file's content. During the runtime there is a probability for this file to be modified by the user. The object has a metho... | You seem to be worried about this appearing on the left hand side, though *this = ... merely calls operator=. Typically the assignment operator that takes a rvalue reference just moves the members.
Consider this simpler example:
struct foo {
int x = 42;
foo& operator=(foo&& other){
x = std::move(other.x... |
70,402,662 | 70,402,985 | How to replace the content of an element in a std::map with the content of another element | I have a class "Token" and a class "ASTNode". ASTNode is a tree representation of a list of "Token"'s.
#define INTEGER "INTEGER"
#define ARRAY "ARRAY"
class Token {
private:
std::string type_t;
std::string value_t;
public:
Token() {
type_t = "";
value_t = ... | Just create a deep copy constructor of ASTNode and everything works well:
ASTNode(ASTNode const & other) {
_token = other._token;
for (auto ochild: other.child)
child.push_back(new ASTNode(*ochild));
}
You may also wish to add similar assignment operator = method implementation (but it is not needed to... |
70,402,974 | 70,412,248 | Why is only static_cast able to return new object of requested type? | Among static_cast, dynamic_cast, reinterpret_cast and const_cast, only static_cast is able to return an object of desirable type, whereas the other type can return only pointer or reference to representation. Why is it so?
Examples:
int y = 3;
double z = reinterpret_cast<double> (y);//error
double z = reinterpret_ca... | I'm making attempt to explain based on example, as addition to other answer that did explain nature of casts.
int y = 3;
double z = reinterpret_cast<double> (y);//error
This is not one of 11 allowed casts with reinterpret_cast. Also std::bit_cast can't cast it on most platforms as the int typically does not have enoug... |
70,403,666 | 70,404,599 | std::views has not been declared | I am trying to use the ranges library from c++20 and I have this simple loop.
for (const int& num : vec | std::views::drop(2)) {
std::cout << num << ' ';
}
I get an error message saying error: 'std::views' has not been declared. I don't get any errors about including the header.
This is my g++
g++.exe (MinGW-W64 x... | Depending on the version of your compiler, different standards are the default. For 11.2 it is C++ 17 AFAIK.
Cou can just add a flag and it compiles:
g++ --std=c++20 main.cc
|
70,403,985 | 70,404,051 | Is there any options to make clang-format produce the following effect? | I use clang-format to format the following code, but the effect is not what I want:
void f(int, int, std::vector<int>, std::map<int, int>)
{}
int main()
{
f(
{
},
{}, {1, 2, 3},
{
{1, 2},
{3, 4},
});
}
Is there any options to make clang-format produce th... | Yes there is, use the style you want. (it's really that easy!)
clang-format -h tells you about the available options that clang-format has.
--style=<string> - Coding style, currently supports:
LLVM, GNU, Google, Chromium, Microsoft, Mozilla, WebKit.
... |
70,404,090 | 70,404,124 | Where to use std::span? | I want to write a function that can accept any type of contiguous buffer (e.g. std::array, std::vector, raw array, etc) from its call site. I have come up with two methods.
Method #1:
void func( int* const buffer, const std::size_t expectedTokenCount );
Here, expectedTokenCount is the maximum number of elements that w... |
Where to use std::span?
Where-ever you would have otherwise used a pointer and a size, you can use std::span instead of the pointer and the size.
Is [#2] a valid ... method?
Sure. You did however change the constness of the pointer. You should use std::span<const int>.
Which one is better?
Each have their uses. B... |
70,404,302 | 70,407,198 | Track text insertion in QTextBrowser | I am making an application and using QTextBrowser to show messages. It should parse ascii colors, so my class (say MessageBoard) is inheriting from QTextBrowser. I can replace ascii color code and set MessageBoard's text color according to the ascii code before insertion.
But there are many ways of inserting text into ... | If I understand your request well, I guess you may want to use this signal https://doc.qt.io/qt-5/qtextdocument.html#contentsChange
You will get access to QTextDocument with this https://doc.qt.io/qt-5/qtextedit.html#document-prop
|
70,404,549 | 70,405,002 | Cartesian product of std::tuple | For unit testing a C++17 framework that relies heavily on templates I tried to write helper template classes which generate a Cartesian product of two sets of data types given by two tuples:
**Input**: std::tuple <A, B> std::tuple<C,D,E>
**Expected output**: Cartesian product of the two tuples:
std::tuple<std::tuple... | One of the workarounds is to omit the function definition and directly use decltype to infer the return type:
template<typename T1, typename T2>
class CartesianProduct {
template<typename T, typename... Ts>
static auto innerHelper(T&&, std::tuple<Ts...>&&)
-> decltype(
std::make_tuple(
std::make_... |
70,404,688 | 70,406,699 | Mismatch between output of ldd --version and ldd -r -v a.out | I am trying to make sense of how output of ldd --version and ldd -v a.out
I have the below simple program
#include <iostream>
#include <string>
#include <cstring>
int main()
{
std::cout << "Hello world" << std::endl;
std::string a = "Test string";
char b[15] = {};
memcpy(b, a.c_str(), 15);
std::cou... | You should read this answer, and look at the output from readelf -V a.out.
When a program is linked, it records the symbol version(s) used (current) at the time of the link.
Many of the symbols your program is using have not changed since e.g. GLIBC_2.2.5, so ldd says: you need at least version GLIBC_2.2.5 (for these ... |
70,405,396 | 70,405,455 | how can I have a public method only show up when the template has a specific type? | I have a template that is intended to take int, float, double, char and std::string.
I want a method to only exist if the template typename is std::string
Is this possible?
| If you can use C++20, you can use a requires expression on the desired method to cause it to only be available under certain circumstances.
#include <iostream>
#include <string>
#include <concepts>
template<class T>
struct Foo
{
void alwaysAvailable() { std::cout << "Always available\n"; }
void conditionallyA... |
70,405,530 | 70,405,777 | Problem extracting formatted input from an istringstream that has been set twice | Thanks for the help.
My program reads lines from stdin. The first one has a single number which determines the mode at which the program is running, and the rest contain sequences of numbers of undetermined length. The number of lines is determined by the mode. I want to parse those lines into vectors of int. To do thi... | Once you read iss >> problem_type;,
cout << "eof: " << iss.eof() << endl;
outputs
eof: 1
The next iss.str(line); does not reset the stream state, the loop condition is false. You want
iss.clear();
while(iss >> input_number) {
cout << " " << input_number;
sequence.push_back(input_number);
}
Output
Stream cont... |
70,405,583 | 70,405,723 | i am always getting segmentation fault | i am always getting 10861 segmentation fault (core dumped) in c++ sorry i came from java
it always says that head -> next how to allocate memory to that
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
class lisp
{
public:
Node *head;
void create(int d)
{
this->hea... | You need to initialize the pointer before assigning some values to it. So, you need Node *add = new Node(); to do so. And suppose you want to append a new node to the list, maybe you need to keep track of the tail of the list (Node *tail). Every time you add a new node, you move the tail.
#include <iostream>
using name... |
70,405,765 | 70,406,500 | Is defining functions in header files malpractice? | We have this header file:
headerA.h
#pragma once
#include <iostream>
void HeaderADefinedFunction()
{
std::could << "HeaderDefinedFunction called!\n";
}
Then inside sourceB.cpp
#include "headerA.h"
void FunctionB()
{
HeaderADefinedFunction();
}
And inside sourceC.cpp
#include "headerA.h"
void FunctionC()
{
HeaderADef... | The code as-shown should produce a link failure with multiply-defined HeaderADefinedFunction() symbol.
The make the code actually valid, the function must be made inline.
Is defining functions in header files malpractice?
Not at all. In fact, template functions must be defined in the header1.
What are the negative a... |
70,406,035 | 70,406,836 | Why don't C++ error messages describe the actual problem in the code? | Why do the Visual Studio error logs show the things caused by some error, rather than the error itself? I often find the error messages to be useless and meaningless.
When I make a mistake, like for example a circular dependency, it throws a bunch of errors like
syntax error: missing ';' instead of something like circu... | Even though this question might be considered out of topic, I'll attempt to give an answer to make it clear why one might find the experssed opinion (useless and meaningless) as "unfair".
Firstly this is not a Visual studio thing. If you've used other C++ compilers (gcc/clang/intel compiler) you'll notice the errors ar... |
70,406,647 | 70,406,667 | Using pointers in Class Templates with Subclasses | I have a problem with using pointers with Class templates. I can't properly access vv from the B subclass if 'vv' stores pointers to vectors; if I simply store vectors it works. But what I'm trying to do requires me to store pointers. I honestly have no idea what I'm doing wrong so here is the code:
template<typename T... | Here:
void add(std::vector<T> new_vec)
{
vv.push_back(&new_vec);
}
You store a pointer to the local argument new_vec in vv. That local copy will only live till the method returns. Hence the pointers in the vector are useless. Dereferencing them later invokes undefined behavior. If you really want t... |
70,406,684 | 70,406,734 | Check whether the first row is filled | I have a matrix, and I want to check whether the first row is filled with "0" or "x"'s.
In my case that means that it's not "-"(empty).
The code below works only for each element of the board but I want it to check for the entire row at once.
bool checkBoardFull(string board[N][N], int n) {
for (int i = 0; i < n; i++)... | Modify the method to not return within the loop:
bool checkBoardFull(string board[N][N], int n) {
bool full = true;
for (int i = 0; i < n; i++) {
if (board[0][i] == "-") {
full = false;
break;
}
}
return full;
}
Or, if you don't want that extra variable:
bool checkBoardFull(string board[N][N], int ... |
70,406,941 | 70,406,987 | Function with parameter pack with sizeof ... (args) == 0 as base case doesn't compile | Here's the code of my function:
#include <iostream>
#include <type_traits>
#include <algorithm>
template <typename Head, typename ... Args>
std::common_type_t<Head, Args...> mx(Head n, Args ... args)
{
if (sizeof ... (args) == 0)
return n;
else
return std::max(n, mx(args ...));
}
int main()
{
... | Even if
if (sizeof ... (args) == 0)
the entire function must be well-formed C++.
return std::max(n, mx(args ...));
This still must be valid C++, even if won't get executed. If, outside of template context, you have an if (1), the else part must still be valid C++, you can't just throw randomly-generated gibberish... |
70,407,273 | 70,409,094 | Merge 2 c++ functions | So I have two codes, one to swap the diagonals of a matrix, and the second is to square root of the moved numbers.
How can I merge these two codes together so that I have an output matrix with interchanged diagonals and squareddiagonals at the same time?
This is the first code - swaps diagonals
#include<bits/stdc++.h>
... | Define and declare the two functions interchangeDiagonals and diagonalsquare and call them in the required order in the main function like this
#include<bits/stdc++.h>
using namespace std;
#define N 3
#define MAX 100
// Function to interchange diagonals
void interchangeDiagonals(int array[][N])
{
// swap elements... |
70,407,696 | 70,407,902 | How to access a 16 bits variable as two 8 bits variables ? And two 8 bits variables as one 16 bit variable | I am using C++17.
Let's imagine I have two variables a and b. These variables are of type uint8_t. I would like to be able to access them as uint8_t but also as uint16_t.
For example :
#include <memory>
int main()
{
uint8_t a = 0xFF;
uint8_t b = 0x00;
uint16_t ab; // Should be 0xFF00
}
I thought that usi... | There are a few other ways to convert between two 8- and one 16-bit value.
But be aware that the results of every solution which directly addresses a single byte in the 16-bit value depend on the byte order of the machine executing it. Intel, for example, uses 'little endian' where the least significant bits are stored... |
70,408,561 | 70,408,929 | How to call qt_sequence_no_mnemonics? | With regards to qt_sequence_no_mnemonics(), the qt documentation says "This function is not declared in any of Qt's header files. To use it in your application, declare the function prototype before calling it."
But what does that mean? I only see this function declared in a cpp file that is not distributed. How do I d... | You can can declare the function by putting this near the top of your .cpp file (maybe just after the #includes):
extern void qt_set_sequence_auto_mnemonic(bool);
... that will tell your compiler that the function exists, so that code later in that same .cpp file can call it without producing a compile-time error, e.g... |
70,408,591 | 70,408,615 | Is there a Standard Untokenize Templated Type? | Is there a standard type to untokenize a type? It'd probably be implemented as so:
template<class T>
using untokenize = T;
This way I can perform the following cast using an overloaded operator:
struct x {
int y;
operator int&() {
return y;
}
};
x a;
// int&(a); // doesn't work
// (int&)(a); // not the same... | It would be more idiomatic to use the correct "named cast" in general. Here, static_cast is appropriate:
static_cast<int&>(a);
That said, there is a standard template that works the same as your other approach, std::type_identity, but only as of C++20:
std::type_identity_t<int&>(a);
|
70,408,799 | 70,409,331 | OpenGL: glColor3f() and glVertex3f() with shader | Can I use glColor3f(), glVertex3f() or other API functions with shader? I wrote a shader for draw a colorful cube and it works fine.
My vertex shader and fragment shader look like this
#vertext shader
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
uniform mat4 model;
uniform... | The glBegin()/glEnd() directives are used in compatibility profile of OpenGL as opposed to core profile which is more modern. However you are compiling your shaders in core profile using the line #version 330 core.
Even if the shaders are not compiled in the core profile, I don't think they'll work since I believe you ... |
70,409,038 | 70,409,349 | Difference between structural type and type returned from contexpr function | I was playing with C++ and got confused by this:
cppreference.com says that a non-type template parameter must be a structural type and that a literal class type is an example of a structural type. Then it says that “Literal types are the types of constexpr variables and they can be constructed, manipulated, and return... | C++20 allows classes as non-type template parameters if they are:
a literal class type with the following properties:
all base classes and non-static data members are public and non-mutable and
the types of all base classes and non-static data members are structural types or (possibly multi-dimensional) array thereof... |
70,409,252 | 70,409,892 | How do I fix Visual Studio 2022 Error E1696 for WinRT | When I generate a new WinRT project in Visual Studio 2022 I get Error E1696 cannot open source file "winrt/Windows.Foundation.h" yet when I look at the Include directories the files do exist at the correct location.
| This is an artifact of the way C++/WinRT works. While the header files do exist in the Windows SDK, that's not where the project goes looking for them. Instead, they are generated on the fly into the source tree under the Generated Files directory.
So to fix the issue you will have to compile a newly created project at... |
70,409,316 | 70,409,798 | what do you mean by base class reference or derived class reference? | I am confused about base class reference and derived class reference in the context of upcasting and downcasting.
In the following code, what is the use of &ref? In the reference, it was marked as a base class reference, to which a derived class obj was assigned.
What is the concept behind this?
#include <iostream>
u... | Even though it is not clear what you're asking, i will try to clear some basics regarding this topic.
First, a reference refers to some other object. A reference is not an object by itself. So lets looks at some examples:
int n = 10;
int &r = n; // Here r is a reference to an int object
Similarly in your code snippet,... |
70,409,358 | 70,409,832 | Can I make error when diamond inheritance with template? | I want to cause an error when inheritance is duplicated. Here is how I found it.
#include <utility>
class Person {};
class Man : public Person {};
class Woman : public Person {};
template <typename... Types>
class merge_class : public Types... {};
template <typename... Types>
struct condition
{
using ... | What you are running into is called diamond inheritance (https://www.makeuseof.com/what-is-diamond-problem-in-cpp/) and IMO is best avoided except for "interfaces". I prefer using composition of implementations also known as the mixin pattern (which in turn uses CRTP, the curiously recursing template pattern). In this ... |
70,409,489 | 70,409,535 | Passing the const-qualified object to the 'std::move' | By doing some code analysis in PVS-Studio, it gave me some warning messages.
I have the following statement in a header file:
constexpr int MIN_ALLOWED_Y { 0 };
And in a source file:
std::make_pair<const int, const int>( std::move( MIN_ALLOWED_Y ), std::move( MAX_ALLOWED_Y ) )
In the above expression, I used std::mov... | Your code:
std::make_pair<const int, const int>( std::move( MIN_ALLOWED_Y ), std::move( MAX_ALLOWED_Y ) )
Is overly complicated. Not only are the moves pointless as PVS Studio told you, but using make_pair when explicitly specifying the types is pointless. You can simplify to:
std::pair<const int, const int>( MIN_AL... |
70,409,548 | 70,409,670 | How to add user defined variable leading zeros in C sprintf? | I am working on a program in which I need to add leading zero for 3 numbers
So the code looks like this
#include <iostream>
using namespace std;
// Check Examples
//Compiler version g++ 6.3.0
int main()
{
long int num =5;
char CNum[10];
sprintf(CNum,"%03ld",num) ;
std::cout << CN... | To make the width dynamic (not hard-coded in the format string), you write it like this:
sprintf(CNum,"%0*ld",blank,num);
Instead of a hard-coded width 3 as in "%03ld", the asterisk indicates that the next argument (which must be of type int) is to be taken as the width.
|
70,410,542 | 70,410,566 | Can one delete a function returning an incomplete type in C++? | In the following example function f() returning incomplete type A is marked as deleted:
struct A;
A f() = delete;
It is accepted by GCC, but not in Clang, which complains:
error: incomplete result type 'A' in function definition
Demo: https://gcc.godbolt.org/z/937PEz1h3
Which compiler is right here according to the s... | Clang is wrong.
[dcl.fct.def.general]
2 The type of a parameter or the return type for a function definition shall not be a (possibly cv-qualified) class type that is incomplete or abstract within the function body unless the function is deleted ([dcl.fct.def.delete]).
That's pretty clear I think. A deleted definitio... |
70,410,689 | 70,410,870 | i am trying to send a 2d vector by reference but seems like its not working for pretty much same approach | 64.minimum-path-sum.cpp: In function ‘int main()’:
64.minimum-path-sum.cpp:67:23: error: cannot bind non-const lvalue reference of type ‘std::vector<std::vector<int> >&’ to an rvalue of type ‘std::vector<std::vector<int> >’
67 | if(minPathSum(vector<vector<int>> {{1 , 2, 3}}) == 12)cout << "ACC\n... | You are calling the function minPathSum creating a temporary object of the type std::vector<vector<int>> using a braced init list.
So the compiler issues an error message that you are trying to bind a temporary object with a non-coonstant lvalue reference.
Just declare the function parameter with the qualifier const
in... |
70,410,865 | 70,413,274 | Inherited struct members inaccessible during aggregate initialization | #include <vector>
#include <string>
struct BasePluginInfo
{
bool bHasGui, bIsSynth;
char cType;
std::string sCategory, sSdkVersion, sVendor, sVersion;
};
struct PluginClassInfo
{
std::string sName, sUid;
std::vector<std::string> vsParamNames;
};
struct ShellPluginInfo : BasePluginInfo
{
std::... | When aggregate initializing something with base classes, the base class acts like a member of the class, similar to if you had:
struct ShellPluginInfo {
BasePluginInfo __base_class_subobject;
std::vector<PluginClassInfo> vciClasses;
};
As such, the first clause in the initializer list will try to initialize it... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.