question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
73,304,742 | 73,304,803 | Does std::make_tuple() not work with objects of type std::optional? | This is the source code:
using namespace std;
class obj {
public:
obj() = default;
obj(int i) : i_{i} {}
int I() const {return i_;}
int const & rI() const {return i_;}
void I(int i) {i_ = i;}
void show() const {cout << "addr = " << this <<... | std::make_optional is a function template. Its purpose is to deduce the tuples types from the parameters passed to it.
Rather than explicitly listing the template arguments you should let them be deduced from the parameter. And you need to actually call the function:
auto get_obj() {
return std::make_tuple(o_0, o_1... |
73,305,510 | 73,306,143 | Does using a pointer to access memory in a loop affect program efficiency? | Here is an illustration:
#include <stdio.h>
void loop(int *a)
{
int b = *a;
for (int i = 0; i < b; ++i)
{
;
}
}
void loop_pointer(int *a)
{
for (int i = 0; i < *a; ++i)
{
;
}
}
int main(void)
{
// Nothing to see here
return 0;
}
In the loop function, the memory... | Yes, referring to objects using pointers can impair efficiency. Consider this code:
void foo(int *a, int *b)
{
for (int i = 0; i < *a; ++i)
*b++ = SomeCalculation(i);
}
After *b++ = SomeCalculation(i);, has the value of *a changed? The compiler cannot know, because the caller might have passed an address f... |
73,305,611 | 73,305,827 | How to exit a function with a return value without using "return" in c++ | How would I exit a function with a return value without using return.
Is there something like this in c++ :
auto random_function() {
printf("Random string"); // Gets executed
exit_with_return_value(/* Any random value. */);
printf("Same string as before"); // Doesn't get executed
}
Because I'm aware abou... | return is a statement. Statements can't be part of a larger expression, so you can't return as a subexpression of some larger expression.
throw is an expression. It can be a subexpression of a larger expression, and you can throw any object you like.
It will be inconvenient for your callers, particularly if you mix it ... |
73,305,616 | 73,305,663 | why can't use ternary operator with different types when boost variable can hold multiple types? | I have something like below, but unable to compile it. I don't get it why I can't have different type when my variable can hold different types?
My code:
#include <boost/variant.hpp>
#include <iostream>
typedef boost::variant<int, float, double, std::string> MultiType;
int main() {
int a = 1;
std::string b = ... | The expression c ? a : b has to have a type. There is no common type between std::string and int, so that expression is invalid.
There is a common type between std::string and MultiType, and between int and MultiType, so c ? MultiType{ a } : b is a valid expression, as is c ? a : MultiType{ b }
|
73,305,805 | 73,305,872 | make -j and #pragma GCC diagnostic | Let's say I add the following to A.cpp
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
<code with unused parameters here>
#pragma GCC diagnostic pop
Then I build with "make -j." If "A.cpp" and "some_other_file_with_no_pragma.cpp" get built in parallel, will the #pragma above apply to b... | Not unless you are doing some really weird stuff in your Makefile.
Compiler compiles each translation unit(.cpp+included .hpp) independently, meaning each pragma only applies to this one translation unit.
Running make -jN will execute N rules in parallel, each (line) in a separate shell process. Resulting in up to N pa... |
73,305,877 | 73,306,730 | How to save the whole raw email on the file system? | I should save the entire structure of the emails that arrive at a mail server.
Using the "poco ++" libraries I was unable to save the email entirely in the file system. For the moment inside the class that inherits from MailMessage I am doing this:
MyMailMessage.h
class MyMailMessage: public MailMessage {
public:
... | The last retrieveMessage() overloaded method should be for you.
void retrieveMessage(
int id,
MailMessage & message,
PartHandler & handler
);
Retrieves the raw message with the given id from the server and copies it to the given output stream.
Check the documentation:
https://docs.pocoproject.org/current... |
73,306,251 | 73,307,340 | Can't compile code with libevent library using CMake | I use CMake in VS Code to build project with libevent. I add it to project
find_package(LIBEVENT REQUIRED)
target_link_libraries(${PROJECT_NAME}
PUBLIC
${LIBEVENT_LIB}
)
target_include_directories(${PROJECT_NAME}
PUBLIC
${LIBEVENT_INCLUDE_DIR}
)
And pass -levent flag to linker
target_link_options(TEST-CMAKE ... | With find_package https://github.com/libevent/libevent/blob/master/cmake/LibeventConfig.cmake.in#L8 you should be able to just:
find_package(Libevent REQUIRED)
add_executable(TEST-CMAKE main.cpp)
target_link_libraries(TEST-CMAKE libevent::core)
|
73,306,373 | 73,487,207 | WIX Toolset MSI. How to pass CustomActionData to a CustomAction using WiX if there are several CustomAction and several Properties in the code? | I trying using this:
How to pass CustomActionData to a CustomAction using WiX?
I have 2 CA and several Properties. CustomActionData using in second CA.
Product.wxs:
<Binary Id="CustomAction1" SourceFile="..\CustomAction1\bin\Debug\CustomAction1.dll"/>
<Binary Id="BinaryId1" SourceFile="..\CustomAction2\bin\Debug\Custom... | Get the value of "CustomActionData" property using MsiGetProperty method. In your case, this method should be called in CustomAction2.
MsiGetProperty(hInstall, TEXT("CustomActionData"), buf, &buflen);
After this, you need to convert returned string into dictionary to get the value of each property.
|
73,307,018 | 73,307,308 | Token-Pasting Operator pasting "Func_foo" and "(" does not give a valid preprocessing token | I am using ## (Token-Pasting Operator) to form a function call.
According to my understanding, a simple example may look like this.
#include <iostream>
#define CALL(x) Func_##x##()
void Func_foo() { std::cout << "Hi from foo()." << std::endl; }
int main() {
std::cout << "Hello World!" << std::endl;
CALL(foo);
... | A token is the smallest element of a C++ program that is meaningful to the compiler.
The ## Token-pasting operator does not concatenate arbitrary printable characters. It concatenates two tokens into one token.
Why the second ## is redundant?
Because concatenating Func_foo and () does not produce a single token.
|
73,307,166 | 73,307,583 | Error while trying to overload operator << for all std container printing, why? | I am trying to build an operator << overload to print all the standard library container types. So far, the overload works well, but when I use it in a generic program, it breaks when I try to print a simple std::string. In fact, this program:
#include <iostream>
#include <utility>
#include <vector>
#include <map>
#inc... | Your operator<< overload may match types for which an operator<< overload is already defined. I suggest that you disable it for such types:
#include <type_traits>
template <template <typename, typename...> class ContainerType,
typename ValueType, typename... Args>
std::enable_if_t<!is_streamable_v<ContainerT... |
73,308,144 | 73,308,267 | What exactly happens when we write if(mp.find()==mp.end()) | I'm currently learning hashmap, I'm facing trouble understanding the iterators, while using it in if statements.
For example,
int main ()
{
std::map<char,int> mymap;
std::map<char,int>::iterator it;
mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;
it = mymap.find('d');
if (it == mymap.en... | From std::map::erase
The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.
Since the below part of the code fails to comply with the above
if (it == mymap.end())
mymap.erase (it);
the program will have undefined... |
73,308,373 | 73,308,374 | Build message: Cannot open include file: 'msoledbsql.h': No such file or directory | My project can't finish build process because I constantly have this error during Visual Studio build: Cannot open include file: 'msoledbsql.h': No such file or directory
I have 'msoledbsql.h' file included in one of the header files.
Does anyone know the solution of this issue?
| After a long research of this issue I found that I've missing msoledbsql.h file on my machine.
The solution for this is to install Microsoft OLE DB Driver for SQL Server. We can find the driver on official Microsoft site Microsoft OLD DB Driver for SQL Server and choose the one suitable for your system architecture (x6... |
73,308,589 | 73,308,710 | unordered_map inside C++ class | I am writing a simple logging class with C++. I want to create an unordered_map to store logging_levels, but compiling fails.
#include <iostream>
#include <unordered_map>
#include <string>
class logging {
public:
std::unordered_map<std::string, int> m_log_levels;
m_log_levels["info"] = 2;
m_log_levels["war... | You can't put arbitrary code wherever you want in a class definition.
Initialize the hash table in a constructor i.e.
class logging {
public:
std::unordered_map<std::string, int> m_log_levels;
private:
int m_level;
public:
logging() { // <<< this is a constructor...
m_log_levels["info"] = 2;
... |
73,308,605 | 73,309,093 | How to write a Character type concept? | The standard library doesn't seem to provide a concept for character types yet. Similar to e.g. std::integral, I want a concept that is suitable for character types (such as char, wchar_t, char32_t, etc.). How should one write a proper concept for this purpose?
Something similar to this could help:
template <typename T... | template< class T >
concept Character =
/* true if T is same as the listed char types below
* do not forget that e.g. same_as<char, T> is true only
* when T is char and not char&, unsigned char, const char
* or any combination (cvref),
* therefore we only remove the const volatile specifiers
... |
73,309,210 | 73,309,321 | Simpler logger function using std::stringstream | I'm trying to write a simple logging function which can handle different types in this format:
LOG("This is one type: " << one_type << " and here is a different type: " << diff_type);
I've been looking at the examples here:
How to use my logging class like a std C++ stream?
stringstream with recursive variadic functio... | A common way to solve this is to make LOG a macro that just does text substitution instead. You could define a LOG macro like
#define LOG(to_log) \
do \
{ \
std::cout << to_log << std::endl; \
} while (false)
and then
LOG("This is one type: " << one_type << " and here is a different type: " << diff_type);
would ... |
73,309,470 | 73,309,768 | Use minitrace in a given namespace in C++ | I'm using minitrace to profile performance of my functions in a namesapce filtration. However, minitrace does not work if functions like MTR_BEGIN() are invoked inside a namespace. The following is my code. My idea is to add namesapce to minitrace.h. Any suggestion on having minitrace work in a namesapce?
#include "min... | I see some functions signature in minitrace.h. I think you can add namesapce like minitrace to these functions.
|
73,309,661 | 73,334,474 | How to interpret complex strings as graph properties when reading a graphML file using `boost::read_graphml`? | I have a graph type where each Vertex carries a std::vector<int> as a property.
struct VertexProperties {
std::vector<int> numbers;
};
using Graph = boost::adjacency_list<
boost::vecS, boost::vecS, boost::undirectedS, VertexProperties>;
I wrote an example object of my graph type to a GraphML file using boost::wr... | I solved my problem by writing a custom property map class template TranslateStringPMap that wraps an existing property map and takes two function objects that convert between strings and the wrapped map's value type.
File translate_string_pmap.hpp:
#ifndef TRANSLATE_STRING_PMAP_H
#define TRANSLATE_STRING_PMAP_H
#incl... |
73,309,856 | 73,310,537 | Why copy intialisation is used instead of direct initialisation when passing argument to function parameter by value | I am learning C++ using the resources listed here. In particular, I came to know that copy initialization is used when passing arguments to function parameters(by value) etc.
For example, from decl.init.general#14:
The initialization that occurs in the = form of a brace-or-equal-initializer or condition ([stmt.select]... | It is precisely so that this does not work.
The whole point of the distinction between copy-initialization and direct-initialization is to prevent implicit conversions in cases of copy-initialization. By using explicit in your constructor, you are declaring that you do not want integers to be converted to C unless the ... |
73,310,337 | 73,310,415 | While I want to use the data members from .h file to the other file | I am using the two .h files and the two .cpp file.
The employee.h file contains
class Employee
{
public:
std::string Name,Id,Address;
};
The second .h file stack.h contains
#include "employee.h"
class Stack
{
public:
int total=0;
void push();
void pop();
void display();
};
The firs... | It seems to me that you are trying to create stack of employees. The way to do this is to put the employees inside the Stack. Like this
class Employee
{
public:
std::string Name,Id,Address;
};
class Stack
{
public:
int total=0;
Employee emp[10]; // 10 employees
void push();
void pop();
void di... |
73,311,181 | 73,311,410 | Explicit instantiation unexpected behavior - breaking ODR does not cause compilation errors | Let's consider the following code:
output_data.hpp
#pragma once
#include <functional>
#include <cstddef>
namespace example {
using Callback = std::function<void(int)>;
struct OutputData {
void * data = nullptr;
std::size_t size = 5;
Callback callback = nullptr;
};
} // namespace example
buffer.hp... |
Why was the code compiled without errors?
Credit to Richard Critten's comment for the source.
"The compiler is not required to diagnose this violation, but the behavior of the program that violates it is undefined"
Is it possible to detect such programming mistakes during compilation?
Yes, see below.
Is there any ... |
73,311,378 | 73,324,817 | Wxsmith how to make WxGrid infinite rows | I want to keep writing data into WxGrid, but i need to set the rows for WxGrid. I've searched some way but the answer that i get is to use Wx.GridTableBase which is for WxPython.
Is there any way to make WxGrid rows infinite?
I'm using codeblocks c++ with WxSmith.
| Okay so i just need to use AppendRows() everytime i need to add rows. it's on the manuals https://docs.wxwidgets.org/3.0/classwx_grid.html
|
73,311,661 | 73,314,450 | Errors in creating a Webview2 sample app in UWP | I am following the steps mentioned here and am able to successfully create the sample app sans webview till Step 5. From Step6 onwards, things go wrong.
This is the current content of my MainPage.xaml:
<Page
x:Class="Webview2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:... |
Errors in creating a Webview2 sample app in UWP
As Raymond Chen points out the code is failing to include the C++/WinRT projection headers for Microsoft::UI::Xaml::Controls. After installing the NuGet package, please go to pch.h and add the following #include directives. For more info you could refer to A basic C++/W... |
73,312,460 | 73,312,539 | Crash when erasing element from unordered_set in loop | I have some code that tries to erase certain elements from an unordered_set. It is done in a loop. The crash happens after it removes the first element found. I currently don't have any other setup except an M1 Mac. The crash happens there but doesn't on online sites (such as Coliru). I am wondering if my code has any ... | Rewrite the for loop like
for (auto it = S.begin(); it != S.end(); ) {
if (it->x == 0)
it = S.erase(it);
else
++it;
}
If the compiler supports C++ 20 then you can just write
std::erase_if( S, []( const auto &p ) { return p.x == 0; } );
Here is a demonstration program
#include <unordered_set>
#... |
73,312,547 | 73,314,719 | Why can't structure initialization work with array of char? | When initializing a struct using curly braces, it does not seem to work with an array of chars. I can write an equivalent constructor that works below. Is there any syntax so I don't have to write the constructor?
#include <cstdint>
#include <cstring>
using namespace std;
struct NamedLocationData {
uint16_t offset;
... | Default constructors are one of the special member functions. If no constructors are declared in a class, the compiler provides an implicit inline default constructor.
I suggest you change char[] to string so that stateName will be able to get a value.
#include <cstdint>
#include <cstring>
#include <string>
using names... |
73,312,585 | 73,313,532 | C++ unicode strings - the basic_strings know nothing about Unicode? | I see here that the C++ standard library now has typedefs of std::basic_string like u8string and u16string, but I don't see any member functions or algorithms that know much of anything about Unicode.
Let's say I want to iterate over the "grapheme clusters" in a string stored as UTF-8. These are the things that humans ... |
Am I right that std::u8string has nothing for that and I need to use a library like ICU?
It appears the substr member function would split a UTF-8 or UTF-16 character in half, so again I need to use ICU or something to make sure I don't do that.
Yes, you are correct, on both counts. The standard C++ library has no c... |
73,312,652 | 73,312,796 | How to setup complex project with Visual Studio 2022? | I have project that I was developing for years in Linux.
It depends on MKL, libxml++, GSL and armadillo library.
Its installation structure is done in CMake and project is formed by building a shared library and couple of executables that link to it. There are about 20 classes in the library.
Project structure is:
--sr... | VS does have support for CMake, although I have no idea how well VS integrates CMake. If you're not set on using VS, you might want to look into an IDE that uses CMake at it's core, Clion comes to mind. That being said, when coming from Linux you don't have the (initial) luxury of simply installing all the dependencies... |
73,312,795 | 73,312,879 | How do you transpose a tensor in LibTorch? | I can't seem to figure out how to transpose a tensor in LibTorch, the (C++ version of PyTorch).
torch::Tensor one_T = torch::rand({6, 6});
int main() {
std::cout << one_T.transpose << "\n";
}
My error...
/home/iii/tor/m_gym/multiv_normal.cpp:53:24: note: mismatched types ‘const std::set<Types ...>’ and ‘at::Ten... | one_T.transpose(0, 1)
The 0, 1 is the type of default transpose used in PyTorch and Numpy without being specified.
|
73,312,905 | 73,313,089 | dllexport a type with a std container of std::unique_ptr results in error C2280 | I'm trying to dllexport a type with a std container of std::unique_ptr member, f.e.
struct __declspec(dllexport) C {
std::vector<std::unique_ptr<int>> c_;
};
but whatever i try, msvc always complains about
msvc/14.33.31629/include\xutility(4145): error C2280: 'std::unique_ptr<int,std::default_delete<int>> &std::un... | When you have a member std::vector<std::unique_ptr<int>> c_;, the compiler will provide a copy assignment operator C& operator=(const C&) that will try to copy the c_ member. This will fail to compile if it is actually used, since the elements of c_ can't be copied.
__declspec(dllexport) seems to try to create this imp... |
73,313,073 | 73,315,313 | CS50 Week5 Speller compiles but is incorrect. Also takes no time on size and unload | I started working on this yesterday. It compiles but whenever I run it with
./speller texts/lalaland.txt
I get this result:
WORDS MISSPELLED: 17134
WORDS IN DICTIONARY: 143091
WORDS IN TEXT: 17756
TIME IN load: 0.04
TIME IN check: 8.41
TIME IN size: 0.00
TIME IN unload: 0.00
T... | There is a problem with the hash function. valgrind will complain about an unitialised value in hash; specifically value. Because value is not initialized, it will have the value that is stored in the memory that is assigned to it. Unpredictable results ensue.
There is also a problem with unload. Once the first node is... |
73,313,128 | 73,313,377 | Automatically declare member pointers to their own classes | My question is:
Is there a way to declare static member pointers to their own classes automatically?
I have a C++ state machine, in which classes have static pointers to their own classes. This means I can bind a given object to the pointer in its class uniquely. In other words, from each class, only 1 instance can be ... | The only thing I can think of would be a CRTP-based approach, something like:
template<typename T> struct current_instance {
static T *ptr;
void bind() { ptr = static_cast<T *>(this); }
};
// ...
template<typename T> T *current_instance<T>::ptr;
//-----------------------------------------------------------... |
73,313,430 | 73,313,445 | How to track mouse dragging? | What event do I need to write in my wxWidgets program so that I can track mouse dragging.
I mean hold down the left mouse button and track the movement while it is pressed.
| Bind(wxEVT_MOTION, [&](wxMouseEvent& event) {
if (event.Dragging()) {
if (event.LeftIsDown()) {
// code
}
}
});
|
73,313,543 | 73,313,582 | Is there a way to get rid of template <class T> on operator overloading? | I would like to know if there is a way to get rid of template <class TI> to make my code more clear (I have an overload for every logic operator, not only operator==). Only in C++98, please.
template <class T>
class iter
{
public:
// some stuff
private:
template <class TI>
friend bool operator == (const it... | Within template<class T> class iter, you may simply use iter to mean iter<T>.
template <class T>
class iter
{
public:
// some stuff
private:
friend bool operator == (const iter& lhs, const iter& rhs);
{
return (lhs._ptr == rhs._ptr);
}
};
|
73,313,547 | 73,313,568 | C++ Passing a template function to another function without specifying the template parameter | Intro
Two weeks ago I started a new project and came along another idea for a project: a test runner for automating tests of template functions - which I'm currently working on.
The main reason behind all that is that I want to
learn more about (modern) C++ and
implement some stuff from my uni lectures.
Said test run... | The closest thing I can think of is,
auto call_add = [](auto&&... args){ return add(std::forward<decltype(args)>(args)...); };
doSomethingWithAdd(call_add);
Of course, you can add a macro for it if it's too complicated.
|
73,313,854 | 73,313,995 | Code not compiling when template functions are placed in a certain order | The following program compiles successfully.
template<typename T>
T sum(T x) {
return x;
}
template<typename T, typename... Args>
T sum(T x, Args... args) {
return x + sum(args...);
}
int main() {
sum(1, 2, 3, 4, 5);
}
However, when I switch the order in which the template functions are written, it... | At the heart of your question is the following issue: when a function name, such as sum, appears inside a function template, what function does it refer to?
You wrote:
Aren't both functions already defined prior to being called in main()? Why does the order in which they're written in matter?
You seem to have the fol... |
73,314,521 | 73,314,605 | c++ child copy constructor not saving member variable | I want to create copy constructor only for the derived class as so:
template <typename T>
class base_list {
public:
base_list() noexcept = default;
base_list(std::initializer_list<T> il)
: list_{il} {}
friend auto operator<<(std::ostream& os, base_list const& sl) -> std::ostream& {
if (s... | What's happening here is somewhat analogous to an old-fashioned game of musical chairs.
You have a
std::list<T> list_;
that's declared as a private member of the base_list. And as an extra bonus you also have a
std::list<T> list_;
that's declared as a private member of the derived_list. They happen to have the same n... |
73,315,164 | 73,317,526 | How to use Objective-C sources' ExplicitInit class? | In the Objc source code, I found the following code. What is the meaning of this code and how to understand it?
objc/Project Headers/DenseMapExtras.h line:38
template <typename Type>
class ExplicitInit {
alignas(Type) uint8_t _storage[sizeof(Type)];
public:
template <typename... Ts>
void init(Ts &&... Args... |
In the Objc source code, I found the following code. What is the
meaning of this code and how to understand it?
To me it looks like a kind-of-factory which can be used as an alternative to the Construct On First Use Idiom. An instantiated class here represents a storage for an instance you can initialise and request ... |
73,315,541 | 73,315,586 | What is wrong with my code? I get an error saying I have no declared 'name' but I do not know how to do this (beginner)? | For this program I am trying to make first ask for the users name, print this as a lowercase, and then make a menu, and then for option 1 the program asks the user to guess a random number between 1-100. When I try to run the below code, the error I get is:
program.cpp:51:11: error: 'name' was not declared in this scop... |
What is wrong with my code? I get an error saying I have no declared 'name'
The problem is that there is no variable named name inside main(). That is, you're trying to read into name using cin>>name; when there is no variable called name that can be used here.
To solve this you can create a variable called name of t... |
73,315,667 | 73,315,936 | How to implement a std::function with operator= that can check if its rhs has same signature | I'm learning to implement std::function and have found several articles about this. Unfortunately, none of their implementations can report a mistake when I assign a funtor with different signature. However, the STL version can alert me as I expect. Obviously, this kind of feature is useful to check such stupid mistake... | Cppreference says about operator=:
Sets the target of *this to the callable f, as if by executing function(std::forward(f)).swap(*this);. This operator does not participate in overload resolution unless f is Callable for argument types Args... and return type R.
This can be easily checked with std::is_invocable_r hel... |
73,315,831 | 73,315,923 | Is post-incrementing the iterator during a container erase always a bug? | Debugging some code, I found an invalid use of an iterator. So I searched our code-base for further bad usages. I found a few of these:
it = cppContainer.erase( it++ );
(Where it is a valid container iterator before this line, and cppContainer is a STL container, e.g. vector).
This sparked a discussion on whether th... |
or whether it was post-incrementing the iterator after the call to the container .erase() made it invalid.
Please note that the arguments are fully evaluated before the function is called. You can conceptually imagine the post-increment as below:
auto operator++(int) {
auto cp = *this;
++*this;
return cp;
}
As... |
73,315,971 | 73,316,118 | Declare C++ Class (identifier logging is undefined) | I'm a complete newbie to C++ so bear with me. I am defining a class called 'logging' which is currently write in main.cpp. Now that I am trying to split implementation (log.cpp) from declaration (log.h), I have the following situation that bring me to compiler error 'identifier logging is undefined':
log.cpp
#include <... | The main problem is that you're defining the class logging twice. Instead you should put the class definition with only the declaration of the members functions in the header and then implement the member functions in the source file as shown below:
log.h
#pragma once
#include <unordered_map>
#include <string>
class ... |
73,316,465 | 73,316,683 | How to use win api to check if the network is a pay-per-traffic link | I see that since windows8 users can set up network as a pay-per-traffic internet link, so maybe some apps will use less data traffic
But I can't find an easy to use api to determine if the current network is billed or not when developing c++ applications
Does anyone have a link to the documentation for this?
| Windows::Networking::Connectivity::NetworkInformation class is what you seek.
The GetInternetConnetionProfile method on this class returns a ConnectionProfile instance. On that object, you can invoke GetConnectionCost to get the NetworkCostType enum property. There's an event you can register a callback for when the ... |
73,316,922 | 73,317,031 | how to understand void (*&&)() func | I use C++ https://cppinsights.io/ to see the progress of instantiation, and there's something puzzled between Function&& and Function.
I comment the code generated by cppinsights.
template<typename Function>
void bind(int type, Function&& func)
{
}
/*
// instantiated from the function above:
template<>
inline void ... |
how to understand void (*&&)() func
First things first, the above syntax is wrong because func should appear after the && and not after the () as shown below.
Now after the correction(shown below), func is an rvalue reference to a pointer to a function that takes no parameter and has the return type of void.
Note als... |
73,317,885 | 73,324,561 | gcc - C++ error "declaration changes meaning" - error appears on linux gcc 11.3, but not on msys2 gcc 12.1. how to force it? | With this code:
enum class profession
{
doctor,
banker
};
class person
{
profession profession;
};
int main()
{
}
on linux (opensuse 15.4 with gcc 11.2), compilation command
g++ -std=c++20 -pedantic -Wall -Wextra -Werror=return-type -Wshadow=local -Wempty-body -fdiagnostics-color -s -Os -o program_gpp pr... | Pass -fno-ms-extensions to MSYS2 GCC. This disables some MSVC-esque extensions.
|
73,318,411 | 73,318,604 | C++ transform std::pair<std::pair<std::pair<A, B>, C>, D> to std::tuple<A, B, C, D> | I have such kind of code:
const auto temp = std::make_pair(std::make_pair(std::make_pair('Q', 1.2),
std::string("POWER")), 1);
std::cout << std::format("({}, {}, {}, {})\n", temp.first.first.first,
temp.first.first.second, temp.first.second, temp.second);
that obviously prints:
(Q, 1.2, POWER, 1)
I want to m... | You can recursively std::tuple_cat
template<typename First, typename Second>
auto flatten(std::pair<First, Second> pair) {
return std::tuple_cat(flatten(pair.first), flatten(pair.second));
}
template<typename... Types>
auto flatten(std::tuple<Types...> tup) {
return std::apply([](auto... args) { return std::tu... |
73,318,618 | 73,318,705 | Qt: Displaying an int in a message box | I have a timer/clock that displays a message X amounts of seconds (usually 10) after it has been clicked. I attempted to set up an int that one could set easily to change what X is, however I am having trouble with displaying the message, which includes the value of X, in a message box.
What I want:
Where the value "1... | You can convert your number to QString like
void MainWindow::messageBox(){
QMessageBox::information(this, "Warning!", "You clicked the button of doom " + QString::number(timerLength/1000) + " seconds ago!");
} //timerLength is an int.
I tried it works in my app.
|
73,318,680 | 73,318,911 | Can the space complexity of a solution using recursive function be O(1)? | I have solved the 98th problem in leetcode
and this is my solution:
class Solution {
public:
long long pre;
bool check(TreeNode *node) {
if(!node) return true;
bool left = check(node->left);
bool mid = node->val > pre;
pre = node->val;
bool right = check(node->right)... | You need O(max tree depth) space for the parameters and local variables. For a balanced tree, that's O(log nodes), and for a maximally imbalanced tree, that's O(nodes).
The stack frame for the call to check(parent) has to exist at the same time as the stack frame for it's call check(parent->left) (and similarly check(p... |
73,318,732 | 73,341,847 | Qt6 - Draw custom metatype in table/tree from QAbstractTableModel | If I have an overridden QAbstractTableModel that supplies a non-qt type, it's my understanding that supplying overloads for the << and >> operators will allow Qt to natively represent those types.
I have prepared an example with std::u16string in an attempt to create the most minimal test case, but can't seem to render... | In my case, it turns out that the << and >> operators weren't needed at all. Instead, providing an appropriate meta type converter allowed for what I wanted.
Sample code for converter:
struct string_converter
{
static QString toQString(const std::u16string& value)
{
return QString::fromStdU16String(valu... |
73,318,893 | 73,319,532 | Application fails to launch via Visual Studio 2003 - CURLE_NOT_BUILT_IN Curl error displayed in debugger | We have a legacy MFC based application in our company which is built with Visual C++98 on Visual Studio 2003. We use curl for Http requests. libcurl.lib file is linked into the project.
I see 2 behaviors while executing the HTTP requests.
When we launch the application from Visual studio or the bin folder directly, I ... | I figured out what the issue was.
libcurl.dll was missing the bin/rel folder and hence CURL was throwing the error CURLE_NOT_BUILT_IN. I have manually copied the file to that folder and the application is working well
|
73,319,796 | 73,322,243 | Why would you declare a std::string using it's constructor? | Most people when declaring strings in C++, or most other languages, do it like so:
std::string example = "example";
However I've seen some code samples where it is done like this:
std::string example("example");
To me it seems like it needlessly obfuscates the code, particularly if there is a using std::string statem... | The practical reason for the second form is that it reflects what actually happens. Your two examples actually - despite their syntactic differences - do exactly the same thing.
They are both calling a constructor which accepts a const char * to initialise example with the literal "example".
The main difference is th... |
73,319,953 | 73,321,989 | What is the difference between lambda capture [&args...] and [...args = std::forward<Args>(args)] | I'm writing a simple game with Entity Component System. One of my components is NativeScriptComponent. It contains the instance of my script. The idea is that I can create my NativeScriptComponent anytime and then Bind to it any class implementing Scriptable interface. After that my game's OnUpdate function will automa... | For added completeness, there's more things you can do. As pointed out in the other answer:
[&args...]() { return make_unique<T>(forward<Args>(args)...); };
This captures all the arguments by reference, which could lead to dangling. But those references are properly forwarded in the body.
[...args=forward<Args>(args... |
73,320,722 | 73,334,755 | Function that takes VectorXf and can modify its values | I am trying to understand how to manipulate Eigen Vector/Matrix. I would like to implement a least-square gauss-newton algorithm (hence why I am learning to use the Eigen library). I have a 1x6 vectors of parameters that I need to update each iteration. Right now, I just want to figure out how a function can take a vec... | I believe the purpose of that section of the documentation is to make you aware of the potential pitfalls that come from the various temporary objects that Eigen creates as it goes through various operations. You can write functions that take writable references such as foo(Eigen::VectorXf &vector) and it will work. O... |
73,320,886 | 73,331,280 | How to link a C++11 program to the Adept library | Adept (http://www.met.reading.ac.uk/clouds/adept/) is a C++ library for automatic differentiation. The following example, placed in a file called home_page.cpp is taken from the home page for the library:
#include <iostream>
#include <adept_arrays.h>
int main(int argc, const char** argv)
{
using namespace adept;
... | As has mentioned in the Adept library documentation, you should add this line to your main source file that includes the main() function:
#include <adept_source.h>
In addition, for every other source file of your code, you may include either adept.h or adept_arrays.h.
|
73,321,368 | 73,375,483 | Camera2 byteArray to BGR uint8 mat conversion | I'm trying to convert byteArray from camera2 onImageAvailable listener to Mat object, and then passing it to an algorithm for dehazing in c++. I have tried different methods available for converting byteArray to Mat channel 3 object but whenever I split the mat object in 3 channels then all of them get filled with garb... | After a lot of discussion over OpenCV forum, the solution to convert ARGB to BRG came out as
Mat argb2bgr(const Mat &m) {
Mat _r(m.rows, m.cols, CV_8UC3);
mixChannels({m}, {_r}, {1,2, 2,1, 3,0}); // drop a, swap r,b
return _r;
}
The link to discussion is here
Besides it, what actually worked for me, was to drop the la... |
73,321,665 | 73,322,819 | How to get real time std out from python script while using QProcess | here my code, real time output i can get only when using ping {address} in QLineEdit as cmd input. i want to same effect, but when execute python test.py.
QT C++ code:
#include "dialog.h"
#include "ui_dialog.h"
#include <QProcess>
QProcess proc;
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::D... | fixed just by add -u flag for execute command.
example:
python3 -u test.py
problem was with buffering.
|
73,321,959 | 73,368,187 | Why mciSendString cannot open my mp3 file? | I am trying to play MP3 audio in C++ Visual Studio 17.3.0, but keep getting MCIERROR 275 followed by 263.
My .mp3 file is in the same directory as my .cpp file.
My code goes something like this:
MCIERROR me = mciSendString(TEXT("open ""Music.mp3"" type mpegvideo alias mp3"), NULL, 0, NULL);
while(true){
me = mciSen... | The first is to open:
mciSendString("open Summer.mp3 alias song",NULL,0,NULL)
Add the relative path or absolute path of the file after open (depending on the relative position of the music you play and your program)
We could understand alias as replacing your music name with the name after alias, which is convenient f... |
73,322,016 | 73,322,237 | Overloading the output operator for a template class and a nested class | There is a template class in which a subclass is nested. How to properly overload the output operator to the stream for an external class, which is a template, in which the output operator to the stream is called from a nested class? In my case, compilation errors occur:
no type named 'type' in 'struct std::enable_if<f... | I think the easiest thing to do is to provide the definition inline with the declaration.
#include <iostream>
#include <memory>
#include <string>
using std::cout;
using std::make_unique;
using std::ostream;
using std::unique_ptr;
template<typename T>
class Nesting {
public:
class Nested {
public:
T d... |
73,322,114 | 73,323,599 | Is it necessarily bad to use const_cast when working with legacy libraries? | I am writing a C++ program for Linux. I use many low-level libraries such as XLib, FontConfig, Xft etc. They are all written in pure C, and in some places in my code I have this annoying problem:
I wrap C structures in RAII-friendly classes, where resources are allocated in constructors and freed in destructors. Freein... |
Is it necessarily bad to use const_cast when working with legacy libraries?
No.
It's generally bad to design code that requires a lot of const_cast, because it suggests you haven't thought very carefully about mutability.
You're using libraries that were written before const-correctness was much considered, and their... |
73,322,173 | 73,322,371 | Runtime Error. Addition of unsigned offset | I was solving Increasing Subsequences in LeetCode and it is giving error continuously.
Tried in different IDEs with same test cases working every time. Even after brainstorming for an hour or two I was unable to find the error. Here is my C++ solution.
class Solution {
public:
vector<vector<int>>ans;
vector<vec... | I was not able to reproduce the santizer message with the input in the question (see https://godbolt.org/z/j4rxGdoYb). However, this condition may wrap around an unsigned integer:
if((prev.size() == 0 && !s.count(v[i])) || (prev[prev.size()-1]<=v[i] && !s.count(v[i])))
When prev.size() == 0 but !s.count(v[i]) is false... |
73,322,232 | 73,322,828 | Parse complex numbers with Boost::Spirit::X3 | I would like to write a Boost::Spirit::X3 parser to parse complex number with the following possible input format:
"(X+Yi)"
"Yj"
"X"
My best attempt so far is the following (Open on Coliru):
#include <complex>
#include <iostream>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/home/x3.hpp>
#i... | So, @Eljay's comment is right...
The issue stems from the use of > instead of >> to allow the failures without triggering the error handler upon failure.
So to actually succeed, we need to use >> in these places:
const auto pure_imag_number = x3::attr(0.) >> x3::double_ >> x3::omit[x3::char_("ij")];
const auto pure_rea... |
73,322,276 | 73,324,258 | Qt passing a Value from one window to antother | I am quite new to programming, so hopefully someone can help me out. After calculating a value with a function and storing it into the variable with a setter, I want to call it in my viswindow.cpp to visualize it in a Graph. In the mainwindow the right value is calculated and stored by pressing a button, which also ope... | Here are examples of:
Single time value transfer from MainWindow to VisWindow in constructor parameter.
Value update from MainWindow to VisWindow by slot-signal chain.
Value update from MainWindow to VisWindow by direct call of VisWindow->updateValue() slot as regular function.
mainwindow.h
#ifndef MAINWINDOW_H
#def... |
73,322,362 | 73,322,363 | Strange behavior of QTableView with text containing slashes | We recently ported a project from Qt 4.8 to Qt 5.15 (Qt 6 isn't an option for us yet due to dependencies).
We're finding that all our QTableViews behave strangely when an item's text contains slashes.
Here is a small program that demonstrates 2 issues:
#include <QTableWidget>
#include <QAbstractItemModel>
#include <QAp... | We were able to find the reasons behind and solutions for these issues after some digging in Qt 5's source code.
The two issues are unrelated.
1) Text elision
After studying the Qt source code for a while, I stumbled on this doc comment for QTableView::setWordWrap:
Note that even of wrapping is enabled, the cell will ... |
73,322,490 | 73,322,649 | Problem with virtual destructor when using template function delete | The following class (with virtual destructor) contains a templated operator delete:
struct S
{
virtual ~S() {}
template <typename... Args>
void operator delete(void* ptr, Args... args);
};
args can be empty, so I think S::operator delete can also be used when a usual delete is expected.
However (using g++)... | Nope! For much the same reason that template<typename T> S(T const&) doesn't define a copy constructor. A lot of C++'s special member functions are required to not be templates. In this instance, a templated operator delete is only selected for use from a placement-new expression.
The reasoning is basically "better saf... |
73,322,716 | 73,324,272 | SetClipboardData and new operator for HANDLE | #include <Windows.h>
int main()
{
HANDLE h = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 4); //new char[4]{ "QWE" };
if (!h) return 1;
strcpy_s((char*)h, 4, "QWE");
OpenClipboard(0);
EmptyClipboard();
SetClipboardData(CF_TEXT, h);
CloseClipboard();
HeapFree(h, 0, 0);
return 0;
}
... | HeapAlloc() returns an LPVOID (void*) pointer, whereas new char[] returns a char* pointer. They are NOT the same type, and neither of them is a valid Win32 HANDLE to a memory object.
SetClipboardData() wants a valid HANDLE pointing to a memory object, but not just any type of HANDLE. Per the SetClipboardData() document... |
73,323,652 | 73,323,724 | class constructor building struct at the same memory location on every instantiation but other members in their own memory locations? | I have a class that when instantiated I build two standard struct members. my instantiation is independent and is in its own memory space every time I build one as is the name member, but the struct's built in the constructor are being given the same memory address every time and thus write over the previous instantia... | This constructor invokes undefined behavior
signal::signal()
{
GenParams GP; //every instance should have its own member GP at a unique mem location
// but instead GP is created at the same mem location
mGP = &GP; // mGP points to the same mem location every time the constructor is called
//fill struct... |
73,324,557 | 73,334,325 | Using return value of _spawnl() to get PID? | The documentation for the _spawn family of functions say they return a HANDLE when called with _P_NOWAIT.
I was hoping to use this handle with TerminateProcess(h, 1);
(In case the started process misbehaves.)
HANDLE h = (HANDLE) _spawnl(_P_NOWAIT, "C:\\temp\\hello.exe", NULL);
However, I don't understand the differenc... | This did the trick:
auto process_handle = (HANDLE)_wspawnv(_P_NOWAIT, argv[1], &argv[1]);
auto procID = GetProcessId(ID);
thanks sj95126
|
73,325,231 | 73,325,268 | Why is the iterator destructor implicitly called? | I'm creating an Iterator interface for my foo class, but while debugging, the iterator's destructor is being implicitly called after the first test.
// Setup for test
// First test
foo::Iterator itr = obj->begin();
int first_value = (itr++)->value; // Destructor called here
// Other tests with itr
I've gone through ... |
postfix increment
Why do you think everyone tells you not to use it? A postfix increment is a prefix increment with an additional copy that has to get constructed and then destroyed for no reason.
This is correct code:
foo::Iterator itr = obj->begin();
int first_value = itr->value;
++itr;
|
73,325,235 | 73,325,667 | How do I get the process ID of something in windows using c++ | I am trying to get the procid of a process using the name of the process. The errors are talking about procEntry.szExeFile. However, I am getting the errors:
[{
"owner": "C/C++",
"code": "167",
"severity": 8,
"message": "argument of type \"WCHAR *\" is incompatible with parameter of type \"const char *\... | You are using TCHAR-based macros, and you are compiling your project with UNICODE defined, so those macros map to the wchar_t-based APIs (ie, PROCESSENTRY32 -> PROCESSENTRY32W, Process32First -> Process32FirstW, etc). As such, the PROCESSENTRY32::szExeFile field is a wchar_t[] array. But, strcmp() expects char* strin... |
73,325,359 | 73,325,626 | C++ Add constraints to a noexcept member function of template class | I have a 3D vector template class and I want to add a normalize member function to it.
Normalizing a vector only makes sense, if they use floating point numbers.
I want to use the c++20 requires syntax with the std::floating_point concept.
template<typename Type>
class vector3 {
[...]
vector3& normalize() require... | noexcept is part of declarator, and requires-clause must come after declarator (dcl.decl)
so you need to write
// from @Osyotr in comment
vector3 & normalize() noexcept requires std::is_floating_point_v<Type>;
|
73,326,790 | 73,366,580 | Visual Studio Code Intellisense doesn't show function documentation for C++ | I followed this C/C++ for Visual Studio Code article from Microsoft to write C++ using Visual Studio Code. Unlike the article showing that intellisense provides documentation for member functions, it doesn't show me any. Same thing also happens in Visual Studio 2019 too. Here is a screenshot of how my intellisense look... | The documentation shown in the mouseover tooltip is generated from the standard library source files configured to be used. The screenshot from the VS Code docs is from a setup using gcc's c++ standard library implementation, libstdc++, which has c++ comments containing that documentation. Since you are using Visual St... |
73,327,414 | 73,327,471 | How to stop strange symbols from being read in the beginning of a getline string C++? | I have this function that imports strings from a .txt file, but when I import using getline the very first string shows up with 3 strange symbols attached to the front. Every other string comes out fine.
I don't know if it's the file itself, but I tried making a new file and it still reads in the strange symbols.
I tri... | Your text file begins with a UTF-8 BOM (0xEF 0xBB 0xBF). You need to either:
create your UTF-8 text files without a BOM present.
just skip past those bytes before reading the rest of the file.
imbue() a UTF-8 locale into your fstream that knows how to recognize and ignore those bytes for you.
|
73,327,446 | 73,327,650 | How do I write SFINAE for copy-list-init in a return statement, in a portable way? | I'm trying to make the following function SFINAE-friendly:
#include <utility>
template <typename T, typename ...P>
T foo(P &&... params)
{
return {std::forward<P>(params)...};
}
I can't put a return statement in a SFINAE context, but since this is an example of copy-list-initialization, I figured I could find a d... | The second version works if you take const& parameter in accept:
template <typename T>
void accept(const T&) noexcept;
|
73,327,998 | 73,328,060 | Exception when escaping "\" in Boost Regex | I'm always getting an exception when trying to escape a backslash like this:
boost::regex shaderRegex{ "test\\" };
Am I doing something wrong?
Unhandled exception at 0x00007FFD13034FD9 in project.exe: Microsoft C++
exception: boost::wrapexcept<boost::regex_error> at memory location
| A literal backslash would be
boost::regex shaderRegex{ "test\\\\" };
In a C++ string, the characters \\ represent a single backslash character.
To represent a regex literal (escaped) backslash, you would need two of those.
If this looks confusing, you can also use a C++11 raw string literal.
boost::regex shaderRegex{ ... |
73,328,097 | 73,395,128 | Implementing Compare for std::set | I have a struct that is just two ints that I want to store in std::set, while also taking advantage of its sorting properties. For example
struct Item
{
int order;
int value;
};
So I wrote a comparator
struct ItemCmp
{
bool operator()( const Item& lhs, const Item& rhs ) const
{
return lhs.order... | based on @retired-ninja 's comment, the answer is to ensure the comparator does proper lexicographical comparison. One shortcut to this is to leverage std::tuple's operators (see https://en.cppreference.com/w/cpp/utility/tuple/operator_cmp ) using this example:
return std::tie(lhs.order, lhs.value) < std::tie(rhs.order... |
73,328,173 | 73,328,268 | Function to print data type to debug console | While searching for any kind of function in could help printing data to debug console, I've found this function here on StackOverflow that can print almost any kind of data:
template <typename Arg, typename... Args>
void doPrint(Arg&& arg, Args&&... args)
{
std::stringstream out;
out << std::forward<Arg>(arg);... | By default, you can't print a std::wstring to a char-based std::ostream, such as std::stringstream, because std::basic_ostream<char> (aka std::ostream) does not have an overloaded operator<< defined for std::wstring (or const wchar_t*).
You could define your own operator<< for that purpose, which converts a std::wstrin... |
73,328,905 | 73,329,269 | Returning empty list to QImage | While browsing through some Qt code, I came across a function that is defined with a return type of QImage, but it's return value is an empty string {}. What does it mean? Couldn't figure it out from the searching I did.
Example:
QImage ExampleRenderer::addImage(QuickMapGL *mapItem, const QString &iconId)
{
if (ma... | Modern C++ requires the compiler to deduce the (still static compile time) type without you needing to type it out. return is one of these cases, it's same as QImage{}, which is same as older style QImage(), meaning default constructed QImage value.
Here is some discussion on this {} initialization, called Uniform Init... |
73,328,916 | 73,329,010 | How to set CMake build configuration in VSCode? | I'm using the CMake Tools extension in VSCode to build and run a C++ project on Windows.
Where do I set if the build configuration should be Debug or Release?
On Build, CMake Tools executes
"C:\Program Files\CMake\bin\cmake.EXE" --build c:/work/foobar/build --config Debug --target ALL_BUILD
How do I get the extension ... | The CMake Tools extension sets up a lot of goodies, including a status bar panel for configuring various aspects of your build(s). In the status line various panels provided by VSCode and extensions can be enabled/disabled. And example including the CMake Tools mini panels appears below:
Note: I am not running VS Code... |
73,329,387 | 73,329,399 | how to control recursion in cpp | Hi I am building a project using cpp in that I am heavily using recursion but I am not able to get
void user1() {
avg=average(totall, dice);
if(avg>=3){
totallSum+=totall;
// cout<<name1<<" is safe! "<<name1<<"'s turn is score now "<<totallSum<<endl;
if(totallSum<point... | It's because the memory is stored in stack (Last in First out).
When its calling user2 function first time then the program will complete its execution first due to Stack memory
after it has executed user2 function then it will continue again back to user1 and move next where it is again calling user2.
To resolve this ... |
73,329,574 | 73,338,215 | MSVC Error C3015 (bad OpenMP for loop) but not an obvious mistake | I'm compiling some C++ code in Visual Studio 2022. I'm using /std:c++17 /O2 /permissive- /openmp:llvm /MP /arch:AVX2 as compiler settings. I'm getting the compiler error
C3015 initialization in OpenMP 'for' statement has improper form
However, I'm feeling like this might be a compiler bug (possibly with /openmp:ll... | As suggested in the comment by @Jerry Coffin, this is a compiler bug that is a regression between x64 msvc 19.31 and 19.32. It turns out this bug has already been reported to Microsoft and a fix is pending release (I would guess in the next minor MSVC update).
|
73,329,767 | 73,329,998 | Google Test Expect Call Function | I am trying to learn google test framework, and I came across an example here. I have something similar to "accepted solution", but I wanted to test it while having class methods as protected.
class GTEST_static_class {
protected:
virtual void display() { std::cout << "inside the GTEST_static_class:: display\n"; ... | Add a friend class GTest_static_example:
class GTEST_static_class {
protected:
virtual void display() { std::cout << "inside the GTEST_static_class:: display\n"; }
virtual ~GTEST_static_class() {}
friend class GTest_static_example;
};
|
73,329,772 | 73,330,076 | How to create a friend function for template base class with constexpr | I want to create a overloaded operator<< for a template base class, that calls the toString function for the child class. The issue is that the toString function of the child class is constexpr, which mean I cannot make it a virtual function of the base class. Here is what I want to do:
template<typename T>
class Base ... | Use CRTP to get access to the derived class:
template <typename T, typename Derived>
class Base {
...
friend std::ostream& operator<<(std::ostream& os, const Base& base) {
return os << static_cast<const Derived&>(base).toString();
}
...
};
class Child1 : public Base<int, Child1> {
...
};
Compiler Expl... |
73,329,912 | 73,329,999 | Whats the difference between a range of a set(a,b) and union of all elements of sets in (a,b)? | Beginner here. Wrote a program to check if entered alphabet is lowercase or upppercase. (Practising if/else questions)
I thought of two methods:
Range method-getting the desired result
Union method-not getting the desired result
Here is the code,
if (enteredAlphabet>='a' && enteredAlphabet <='z')
{
cout<<enteredA... | The expression 'a'||'b'||... is actually a short-hand for ('a' != 0) || ('b' != 0) || ....
The result of the expression will always be the boolean value true.
Since true can be converted to the integer value 1 your comparison is really the same as enteredAlphabet == 1. This comparison will likely never be true.
What yo... |
73,329,974 | 73,330,041 | Why is max_element not showing the largest string in vector C++? | In the code below I attempt to print the largest std::string in a std::vector using std::max_element.
I expected the output of the code below to be:
Harmlessness
The actual output I got is:
This
The code:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
vector <string> s... | The default comparator for std::string does an lexicographic comparisson (see: std::string comparators).
The string "This" comes later in this order than any string starting with "H".
You can use another overload of std::max_element that accepts an explicit comparator argument:
template<class ForwardIt, class Compare>... |
73,330,007 | 73,330,695 | C++ conditionally call functions based on type of the template parameter | Suppose that I have a couple of functions to process different types of arguments. For example processInt for processing int variables and processString for processing std::string variables.
int processInt(int i)
{
return i;
}
string processString(string s)
{
return s;
}
And, I have a template function call... | All branches should be valid, even if branch is not taken.
C++17 has if constexpr which would solve your issue
template<typename T>
T foo(T value)
{
T variable;
if constexpr (std::is_same<T, int>::value)
{
variable = processInt(value);
}
else if constexpr (std::is_same<T, string>::value)
... |
73,330,290 | 73,331,662 | From one argument make two - at compile time | I'm writing a special print function that produces a cstdio printf - statement at compile time. The idea is basically that you invoke a function special_print() with a variadic parameter list and the function will assemble the necessary printf - statement at compile time. Here's what I've got:
#include <cstdio>
#includ... | My initial thought is to forward each arg through a tuple, and then "varags apply" in the call.
template <typename T>
auto expand(T&& t) { return std::forward_as_tuple<T>(t); }
auto expand(std::string_view s) { return std::tuple<int, const char *>(s.size(), s.data()); }
template <typename... Ts>
void special_print(Ts... |
73,330,658 | 73,345,749 | Cuda lambda vs functor usage | I've got a simple function in CUDA using a functor
struct MT {
const float _beta1;
const float _mb1;
MT(const float beta1, const float mb1) : _beta1(beta1), _mb1(mb1) { }
__device__
float operator()(const float& op, const float& gradient) {
return _beta1 * op + _mb1 * gradient;
}
}... | Your example and example_crash functions don't make sense to me because I don't know what _mt is and you don't seem to be using d_weights.
If we fix that, then there are at least a couple issues with your lambda, one of them being there is no __device__ decoration (which is necessary, here).
Making various changes, and... |
73,330,823 | 73,331,413 | ListView_GetNextItem always returning 0 | I have some code that currently causes an infinite loop and I'm unable to find an reason as to why.
The code is designed to set bit-flags on an integer based on items that are selected in the listbox.This is handled by the case statement within the While loop.
I've followed the code through on a debugger and the value ... | LVM_GETNEXTITEM is listview control message, but your control is a listbox. They're different controls and the messages aren't interchangable.
To get the selected items from a multi-select listbox you need to use LB_GETSELCOUNT to get the number of selections, allocate an array of ints that size, and then use LB_GETSEL... |
73,331,060 | 73,342,337 | What does .word 0 mean in ARM assembly? | I'm writing a C++ state machine for Cortex-M4.
I use ARM GCC 11.2.1 (none).
I'm making a comparison between C and C++ output assembly.
I have the following C++ code godbolt link
struct State
{
virtual void entry(void) = 0;
virtual void exit(void) = 0;
virtual void run(void) = 0;
};
struct S1 : public State... | The C++ ABI for ARM and the GNU C++ ABI define which entries must appear in the virtual table.
In the case of your code, the first two entries are the offset to the top of the vtable and the typeinfo pointer. These are zero for now, but may be overwritten if required (eg: if a further derived class is made).
|
73,331,374 | 73,331,427 | How does std::unordered_map differentiate between values in the same bucket? | I know that std::unordered_map handles key hash collisions by chaining keys with the same hash in a bucket (I think using a linked list). The question I have is how does it know which value, in the same bucket, corresponds to which key?
The naive idea I have is that each value is stored in a std::pair, is this how it i... | Yep, that's basically how it's done. Keep in mind that the key is part of the data. One of the things you can do with a map is iterate through its key/value pairs. This would be impossible, even with perfect hashing, if the key itself were not stored.
|
73,331,712 | 73,332,465 | How to elegantly flip a BOOL, without a warning? | I want to simply flip a BOOL variable, but this generates a lnt-logical-bitwise-mismatch warning.
Is there an elegant solution to this?
BOOL bCloseButtons = FALSE;
bCloseButtons = !bCloseButtons; // Intellisense generate a logical-bitwise mismatch
bCloseButtons = bCloseButtons ? FALSE : TRUE; // works... | Use a bool value in your code instead. Flipping a bool is a simple matter of applying the unary !-operator, e.g. value = !value;.
Passing a bool value into an API that expects a BOOL (aka int) value implicitly performs integral promotion from bool to int. This is well defined and will not trigger any warnings.
Likewise... |
73,332,157 | 73,496,996 | Visual Studio 2022 intellisense cannot find Openssl (ARM64 - Makefile project - SSH - Ubuntu) | (Only to be clear, this question is regarding Intellisense only)
Here is my developing scenario:
Visual Studio 2022 (Enterprise edition, 64 bits)
C++ project (Run by SSH to a Raspberry Pi 4 - ARM64 using Ubuntu 20.04 server)
Project is a Makefile project (not CMake).
The code compiles and runs in the Raspberry Pi (vi... | I made progress in solving the problem in an unexpected way. As the project built successfully in the remote machine, I ignored the Intellisense problems for a while. But one day I connected to another machine and there were no problems! Intellisense found all the files.
The machine with problems had Ubuntu 20.04 and t... |
73,332,564 | 73,332,662 | What is the time complexity of new and delete for primitive VS user-defined data types? | From what I gathered, it depends on the implementation of the constructors and destructors for user-defined data types.
I was wondering if there is set time complexity / any guarantees for primitive data types allocation?
| No, there's no such guarantee. Lacking constructors, the time complexity is entirely due to the underlying operator new which has to find free heap storage.
Note that some operator new call is also needed for classes, but this could be either the global ::operator new or a class member. In both cases, it too needs to f... |
73,332,642 | 73,355,270 | C++ with Crow, CMake, and Docker | Goal
I would like to compile an Crow Project with CMake and deploy it in a docker container.
Code
So far, I compiled in Visual Studio and installed Crow via VCPKG similar to this Tutorial.
example main.cpp from Crow website:
#include "crow.h"
//#include "crow_all.h"
int main()
{
crow::SimpleApp app; //define your ... | After further research and testing I could solve this issue on two ways:
Crow.h Project compiled with CMake in Docker container
Dockerfile
# get baseimage
FROM ubuntu:latest
RUN apt-get update -y
RUN apt-get upgrade -y
# reinstall certificates, otherwise git clone command might result in an error
RUN apt-get install -... |
73,332,656 | 73,332,713 | How to fix a copy constructor that doesn't work? | I'm trying to simplify my code. Why I can't use the commented constructor instead of the previous (not commented) one?
struct Direction {
const double x, y, z;
Direction(double _X, double _Y, double _Z) : x(_X), y(_Y), z(_Z) {}
Direction(Direction& _D) : x(_D.x), y(_D.y), z(_D.z) {}
}
class Movement {
priv... | The error message is rather clear:
<source>: In copy constructor 'Movement::Movement(Movement&)':
<source>:15:44: error: binding reference of type 'Direction&' to 'const Direction' discards qualifiers
15 | Movement(Movement& _M) : v(_M.v), d(_M.d) {} // this doesn't work
| ... |
73,332,890 | 73,333,022 | Problem assigning integer a value from an array index | I am trying to create a function that takes a string as an input and extracts the first digit as an output. Here is the relevant code. I am new to coding so tips are appreciated.
int extractNum(string id){
int num=0;
bool found=false;
for(int i=0; i<id.length(); i++){
if(isdigit(id[i])){
... | Your restult num is an integer, but the "2" in your string is a character. When you assign num=id[i], you're converting the character "2" to its ASCII value, which is 50.
So, you need to convert that. The simplest way would be to just do num = id[i] - '0'. That works because in ASCII, numbers are consecutive with "0" b... |
73,332,899 | 73,333,082 | use std::move twice when an argument is passed by value? | I need some feedback in order to see if I understand C++ move semantics correctly. Can someone tell me if the following example of using std::move - including the statements made in the comments - is correct? (No elaborate comments required if the answer is simply Yes)
#include <string>
#include <utility>
class MyClas... | You understood it correctly.
Also you can make your own class, log all constructors and check it by yourself.
|
73,332,909 | 73,333,009 | Does resize on a std::vector<int> set the new elements to zero? | Consider
#include <vector>
int main()
{
std::vector<int> foo;
foo.resize(10);
// are the elements of foo zero?
}
Are the elements of foo all zero? I think they are from C++11 onwards. But would like to know for sure.
|
Are the elements of foo all zero?
Yes, this can be seen from std::vector::resize documentation which says:
If the current size is less than count,
additional default-inserted elements are appended
And from defaultInsertable:
By default, this will call placement-new, as by ::new((void*)p) T() (until C++20)std::co... |
73,333,103 | 73,333,143 | Assigning a new size to a dynamic array in a class - A question from a test | I'm trying to figure out why in this piece of code, every time the function f() is called, the function calls the destructor and does not reallocate the size of the array
I know if I change it to int f(A & a) { return 2 * a.n; }
it will work, but I still don't understand why it goes into the destructor.
class A {
pu... | Every time f(A a) returns, the parameter a used in the call is destroyed.
|
73,333,198 | 73,333,930 | C++ best practice for overloading inherited class | Is this the proper (best) way to initialize both the constructor of the parent class (in this case an interface) and the constructor of the child class?
class Parent {
protected:
int x, y;
private:
int pvt = 2;
public:
int pub = 3;
Parent(int n1, int n2)
: x(n1), y(n2) {}
virtual void merg... | Everything looks OK, EXCEPT you need to declare a virtual destructor in your base class.
class Parent {
public:
virtual ~Parent() = default;
};
If you do not do this the destructor in your derived class will not be called when attempting to delete a pointer of type Parent.
Parent* parent = new Child{1, 2, 3};
// ... |
73,333,218 | 73,333,342 | Strange effect with Nulltermination char inside of string | Simple Code example: Godbolt-Compiler Explorer
#include <cstdint>
#include <iostream>
using namespace std;
using u16 = uint16_t;
int main(){
//char str[] = "0123456789\0abcdefghijklmnopqrtsuvwxyz";
char str[] = "0123456789\00123456789\00123456789";
auto str_len = (sizeof(str)-1);
cout << "stringlength: " <... | The easiest way to stop this from being interpreted as an octal escape sequence would be:
char str[] = "0123456789\0" "0123456789\0" "0123456789";
Or just use \000 as the null character:
char str[] = "0123456789\0000123456789\0000123456789";
|
73,333,832 | 73,333,924 | initializing of a struct of whose members are array of another struct | I have
#include <iostream>
typedef struct coordinate{
double x;
double y;
}point;
typedef struct sc_cell{ // single cell
point sc[4];
}cell;
typedef struct sb_body { // for single body
point sb[4];
}body;
using namespace std;
int main()
{
body r_plate = {};
r_plate.sb[0] = { 0,0 };
... | The structure body is an aggregate that contains data members that in turn are aggregates.
You need to write
body r_plate = { { { 0,0 },{ 5,0 },{ 5,1 },{ 0,1 } } };
That is the structure body contains an array so you have to write
body r_plate = { { ... } };
and each element of the array is an object of the structure... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.