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
|
|---|---|---|---|---|
74,300,516
| 74,300,949
|
The while loop doesn’t stop on a boolean condition
|
I wrote a simple code to solve an artificial problem. I want the program to exit the loop body after N =< 3, but the iterations continue after the condition isn't met. Where did i go wrong?
int main(){
uint8_t N = 0;
int power = 1;
std::cin >> N;
while (N >= 4){
power *= 3;
N -= 3;
}
power *= N;
std::cout << power;
return 0;
}
gcc 12.2.0. Flags -Wall -O2
I tried to use a loop for (N; N >= 4; N -=3), but result didn't change.
|
uint8_t is char type.
In stdint.h,
typedef unsigned char uint8_t;
'4' will be resulted in integer 52 due to implicit casting.
You may just use int type if you are accepting number.
|
74,300,697
| 74,300,770
|
while loop doesn't loop in c++
|
So i just started C++ yesterday, I had a fair bit of java experience so that be the cause idk,
I try to run this code and for some reason the while loop isn't looping, i tried changing the if break statement from ask==false to ask=false, that just ends up with an infinite loop without even taking user input.
Here's the code:
#include <iostream>
#include <math.h>
using namespace std;
int main(){
double raduis;
const double pi = 3.14;
bool ask;
while(true){
cout << "Enter the raduis of the circle:"<< endl;
cin >> raduis;
double circ = 2*pi*raduis;
double area = pi*pow(raduis,2);
cout << "The Circumference of the circle is: "<< circ <<endl;
cout << "The Area of the circle is: "<< area<<endl;
cout <<"Would you like to run again?"<< endl;
cin >> ask;
if(ask==false){
break;
}
}
}
I've tried changing the bool to a char value with "y" or "n" values but to no avail nothing works.
Edit: Okay so I've solved the problem, as per @zdf 's suggestion I entered cin >> boolalpha >> ask; and it works perfectly now.
|
Call clear on cin before the input and make sure the input is only 0 or 1,
From cppreference:
If the type of v is bool and boolalpha is not set, then if the value to be stored is 0, false is stored, if the value to be stored is 1, true is stored, for any other value std::ios_base::failbit is assigned to err and true is stored.
|
74,301,738
| 74,302,037
|
cpp vector erase by indices too slower than python
|
I want to delete items in vector by indices in cpp code. However it is too slow
cpp version
long remove_cnt = 0;
for (auto &remove_idx : remove_index) {
mylist.erase(mylist.begin() + (long) remove_idx - remove_cnt);
remove_cnt++;
}
python version
new_mylist = [item for i, item in enumerate(mylist) if i not in remove_index]
I expect that cpp is faster than python. But my cpp code is too slower than python code. Are there other efficient code in cpp??
|
Your question is a good example of why a 1-1 translation between languages usually doesn't work.
To efficiently erase items from a vector you don't do it by index.
Assuming you got your indices in python by evaluating some condition (a predicate). You can directly use this predicate in C++.
Say you want to remove all ints > 4 then the code looks like this:
#include <algorithm>
#include <iostream>
#include <vector>
bool greater_then_4(const int value)
{
return value > 4;
}
int main()
{
std::vector<int> values{ 1, 2, 3, 4, 5, 6, 7, 8 };
// https://en.cppreference.com/w/cpp/algorithm/remove
// remove all values greater then 4. remove will actually move all those values till the end
auto it = std::remove_if(values.begin(), values.end(), greater_then_4);
// shrink the vector to only include the items not matching the predicate
values.erase(it, values.end());
for (const auto value : values)
{
std::cout << value << " ";
}
return 0;
}
|
74,301,886
| 74,302,056
|
How to sort integer array in descending order (but starting at index 0 and moving up)?
|
my question has to do with sorting an integer array into descending order, but I've got a very specific problem and was wondering if there's a way to solve it without destroying the binary search function I also implemented.
My project overall is perfect, but has one problem which is a dealbreaker according to my instructor. I read a txt file into an array and list them, then sort them into descending order, and have a function to binary search for what index a number is in. My numbers are sorted in descending order and print as such (144, 115, 100, 89, etc). This is GOOD. This is what we want. But when reading the index, 144 is listed as index[19], 115 as index[18] and so on. This is BAD. I would like to maintain the exact same output, but have the highest number be at index[0], then index[1], and be ordered like that.
Here is a picture of what my program looks like.
I'm a little confused as to how to accomplish this. I've tried a few things but regardless of how I do the sorting, the highest numbers are at the highest point on the index.
Here are the relevant bits of my code.
int binarySearch(int array1[], int p, int r, int num) {
if (p <= r) {
int mid = (p + r) / 2;
if (array1[mid] == num)
return mid;
if (array1[mid] > num)
return binarySearch(array1, p, mid - 1, num);
if (array1[mid] < num)
return binarySearch(array1, mid + 1, r, num);
}
return -1;
}
int main() {
int array1[20]{}; //The array that stores the numbers.
char letters[15]{}; //The array that stores the characters.
ifstream inputData("input.txt"); //This assumes input.txt is stored in the same folder.
int n = 0; //Counter for the arrays
int num; //This is for the binary search function.
char x{};
// Error checking for making sure the file can open
if (!inputData)
{
cout << "Cannot open file.\n";
return 0;
}
else {
cout << "The unsorted list of integers: \n";
for (int n = 0; n <= 19; n++) {
inputData >> array1[n];
if (inputData.fail()) break;
cout << array1[n] << " ";
}
cout << "\n\nThe sorted list of integers in descending order: \n";
int n = sizeof(array1) / sizeof(array1[n]); //I have also tried replacing this line with just "int n = 20" and it didn't appear to make any real difference.
sort(array1, array1 + n);
for (int n = 19; n >= 0; n--)
cout << array1[n] << " ";
//When copy-pasting my code across I might be missing a curly bracket or two, don't worry about that stuff.
cout << "\n \nEnter an integer to search: ";
cin >> num;
int index = binarySearch(array1, 0, n - 1, num);
if (index == -1) {
cout << num << " could not be found. Please restart the program and try another number.";
}
else {
cout << "Integer " << num << " found at index [" << index << "] in the sorted integer array.";
}
I feel like I must be missing something obvious. Please help, because I cannot get this array working properly. Occasionally when I mess about, it also stops my binary search from working properly, and it can't detect anything, so I need to tread carefully.
|
In the code, you sort the array with
sort(array1, array1 + n);
That will be ordered using the less-than < operator, which will sort it in ascending order.
But when you display it:
for (int n = 19; n >= 0; n--)
cout << array1[n] << " ";
which you do in reverse order (making it seem like it's sorted in descending order). If you display it in the right order, from 0 to 19 then it will be shown in the actual sorted order.
To sort in descending order you need to use std::greater instead:
std::sort(array1, array1 + n, std::greater{})
And display in the correct order:
for (int value : array1)
std::cout << value << ' ';
|
74,302,290
| 74,344,336
|
How to disable DPI scaling in wxWebview in wxWidgets?
|
I am working with the wxWebView of wxWidgets 3.2.1 in Windows 10. I am also using the Edge backend (WebView2). I have a problem in High DPI monitors and that's the automatic scaling of the Edge. I don't want this automatic scaling and prefer to set the font size manually with the use of some helpful functions like FromDIP. Apparently setting font does not work in this case.
I have seen a way to disable this feature in Chrome by command options like below (Ref) but don't know how to do this in wxWidgets.
--high-dpi-support=1 --force-device-scale-factor=1
Update: In the source of the page, I have a style tag and font is set there and I have the ability to change this font on DPI change event. Currently I don't change the font on the event.
|
It seems that there is not any way to disable scaling feature in Edge via wxWidgets. Therefore because of this automatic upscaling in Edge, I had to downscale my font size first with the use of GetDPIScaleFactor().
|
74,302,381
| 74,303,303
|
boost::lexical_cast can convert hex inside string to int?
|
I see in this topic C++ convert hex string to signed integer that boost::lexical_cast can convert hexadecimal inside string to another type (int, long...)
but when I tried this code:
std::string s = "0x3e8";
try {
auto i = boost::lexical_cast<int>(s);
std::cout << i << std::endl; // 1000
}
catch (boost::bad_lexical_cast& e) {
// bad input - handle exception
std::cout << "bad" << std::endl;
}
It ends with a bad lexical cast exception !
boost doesn't support this kind of cast from string hex to int ?
|
As per the answer from C++ convert hex string to signed integer:
It appears that since lexical_cast<> is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast and my hand rolled one don't deal well with hex strings.
Also, as per boost::lexical_cast<> documentation
The lexical_cast function template offers a convenient and consistent form for supporting common conversions to and from arbitrary types when they are represented as text. The simplification it offers is in expression-level convenience for such conversions. For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional std::stringstream approach is recommended.
So for more involved conversion, std::stringstream is recommended.
If you have access to C++11 compiler, you can use std::stoi to convert any hexadecimal sting to an integer value.
stoi prototype is:
int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );
Your program can be converted to
int main() {
std::string s = "3e8";
auto i = std::stoi(s, nullptr, 16);
std::cout << i << '\n';
}
And the output will be
1000
|
74,302,474
| 74,302,557
|
Initializing std::map with MFC objects doesn't compile
|
MFC beginner here.
I've tried to initialize std::map like this: (in the header of CView)
// myprogramView.h
std::map<int, CStatic> myMap = {{10,{}}, {11,{}}};
But the compiler complains "no instance of constructor ... matches the argument list".
(Edit for future reference) The above message was an error from IntelliSense. The compiler(MSVC) says: C2664 'std::map<int,CStatic,std::less,std::allocator<std::pair<const _Kty,_Ty>>>::map(std::initializer_list<std::pair<const _Kty,_Ty>>)': cannot convert argument 1 from 'initializer list' to 'std::initializer_list<std::pair<const _Kty,_Ty>>'
However, we can do these kinds of initializations:
std::map<int, std::string> myMap2 = { {10,{}}, {11,{}} };
std::map<int, std::map<std::string, int>> myMap3 = { {10,{}}, {11,{}} };
Why doesn't the first example compile, and how can I use a map containing MFC objects?
I'm trying to access the control object in the map and .Create() it during the run-time or in the OnCreate.
I also tried CMap but it seems the same problem occurs.
Question resolved by j6t's answer. Just want to clarify that the answer is talking about std::initializer_list, not 'member initializer list'.
|
MFC objects that derive from CObject (like CStatic) cannot be copied; they have a deleted copy constructor. But initialization from an initializer list requires objects that are copy-constructible.
|
74,302,653
| 74,317,902
|
fmt lib check variadic templates arguments with FMT_STRING at compile time
|
I'm creating my own logger implementation. To format the log message I'm using the great FMT lib.
I'd like to check all passed format arguments at compile time using FTM_STRING.
I'm having 2 problems
The following results in a compiler error "call to immediate function is not a constant"
is it possible to combine default arguments (in my case std::source_location loc = std::source_location::current() with variadic templates.
I haven't been able to omit the
std::source_location::current()
in actual function call
LoggerTask::log("foo {}",std::source_location::current(),1);
.
#include <fmt/format.h>
#include <string>
#include <string_view>
#include <source_location>
class LoggerTask
{
public:
template <typename... Args>
static void log(
const std::string_view strMessageToFormat,
const std::source_location loc = std::source_location::current(),
const Args&... args
);
private:
static void log(
std::string& strFormatedDebugMessage,
const std::source_location loc
);
};
template<typename ...Args>
void LoggerTask::log(
const std::string_view strMessageToFormat,
const std::source_location loc,
const Args&... args
)
{
std::string strFormatedMessage = fmt::format(FMT_STRING(strMessageToFormat), args...);
log(strFormatedMessage, loc);
}
void LoggerTask::log(
std::string& strFormatedDebugMessage,
const std::source_location loc
)
{
//write some actual log
}
int main() {
fmt::print("The answer is {}.", 42);
LoggerTask::log("foo {}",std::source_location::current(),1);
}
Godbolt link: https://godbolt.org/z/8cM119WPz
Could you help me out? Thx guys :)
|
The problem is that you are calling FMT_STRING with a runtime string_view which cannot be checked at compile time.
Moreover FMT_STRING is a legacy API for older compilers. It is recommended to use fmt::format_string instead:
template<typename... Args>
void LoggerTask::log(fmt::format_string<Args...> fmt,
std::source_location loc,
Args&&... args) {
std::string msg = fmt::format(fmt, std::forward<Args>(args)...);
log(msg, loc);
}
See also https://fmt.dev/dev/api.html.
|
74,304,193
| 74,304,563
|
QRandomGenerator gives all the time same values
|
im new in QT/c++ so i have one question, QRandomGenerator genereate same numbers all the time ? I try to make something, random choice a vectors:
int index;
QRandomGenerator num = QRandomGenerator();
index = num.bounded(6);
if (index == 0){
return dmpcY1;
}else if (index == 1){
return dmpcY2;
}else if (index == 2){
return dmpcY3;
}else if (index == 3){
return dmpcY4;
}else if (index == 4){
return dmpcY5;
}else if (index == 5){
return dmpcY6;
}else if (index == 6){
return dmpcY7;
}
and that isnt work. All the time i get same dmpcY1 (in the same program cycle).
bb
I expecting every time when i push the button, code choice different dmpc.
|
Please consider taking another look at the documentation for QRandomGenerator:
You are always creating a new random generator while using the default constructor with seed value of 1, resulting in always the same pseudorandom number to be generated
QRandomGenerator::QRandomGenerator(quint32 seedValue = 1)
Initializes this QRandomGenerator object with the value seedValue as
the seed. Two objects constructed or reseeded with the same seed value
will produce the same number sequence.
As stated in the documentation it might be better to use QRandomGenerator::global()
QRandomGenerator::global() returns a global instance of QRandomGenerator that Qt will ensure to be securely seeded. This object is thread-safe, may be shared for most uses, and is always seeded from QRandomGenerator::system()
|
74,304,301
| 74,304,572
|
Invalid constraint expression
|
The following code example doesn't compile with Clang 15 or Clang trunk, in contrast to GCC 12.2 and MSVC 19.33. Is the contraint expression in the nested required clause invalid?
struct t {
constexpr auto b() const noexcept
{ return true; }
};
template<typename T>
concept c = requires(T t) {
requires t.b();
};
static_assert(c<t>);
The error message produced by Clang:
<source>:11:1: error: static assertion failed
static_assert(c<t>);
^ ~~~~
<source>:11:15: note: because 't' does not satisfy 'c'
static_assert(c<t>);
^
<source>:8:14: note: because 't.b()' would be invalid: constraint variable 't'
cannot be used in an evaluated context
requires t.b();
^
Interestingly, the fault also becomes apparent with GCC when wrapping the evaluation of t.b() in a std::bool_constant. When changing the constraint expression as such:
template<typename T>
concept c = requires(T t) {
requires std::bool_constant<t.b()>::value;
};
GCC will actually produce the following error, while MSVC is still fine with it:
<source>:15:38: error: template argument 1 is invalid
15 | requires std::bool_constant<t.b()>::value;
|
[expr.prim.req.general] (emphasis mine)
4 A requires-expression may introduce local parameters using a parameter-declaration-clause ([dcl.fct]). A local parameter of a requires-expression shall not have a default argument. Each name introduced by a local parameter is in scope from the point of its declaration until the closing brace of the requirement-body. These parameters have no linkage, storage, or lifetime; they are only used as notation for the purpose of defining requirements. [...]
You are trying to use a non-existent object in (constant-)evaluation of an expression, it's not meant to work. Think of the parameters of compound requires expression as shorthand declval. You can use them in unevaluated contexts, examine the types and such, but not evaluate with them.
To be explicit
[expr.prim.req.nested]
2 A local parameter shall only appear as an unevaluated operand within the constraint-expression.
[Example 2:
template<typename T> concept C = requires (T a) {
requires sizeof(a) == 4; // OK
requires a == 0; // error: evaluation of a constraint > variable
};
— end
So Clang is the only correct compiler out of the bunch.
|
74,305,847
| 74,306,250
|
stringstream operator>> fails to assign a number in debug
|
I have this simple function that, given a string str, if it is a number then return 'true' and overwrite the reference input num.
template <typename T>
bool toNumber(string str, T& num)
{
bool bRet = false;
if(str.length() > 0U)
{
if (str == "0")
{
num = static_cast<T>(0);
bRet = true;
}
else
{
std::stringstream ss;
ss << str;
ss >> num; // if str is not a number op>> it will assign 0 to num
if (num == static_cast<T>(0))
{
bRet = false;
}
else
{
bRet = true;
}
}
}
else
{
bRet = false;
}
return bRet;
}
So I expect that:
int x, y;
toNumber("90", x); // return true and x is 90
toNumber("New York", y); // return false and let y unasigned.
On my machine, both debug and release configurations works fine, but on the server, only with the debug configuration, in calls like toNumber("New York", y) the 'ss >> num' fails to recognize that str is a string.
I checked the project configuration, but they are the same for both machines (the server is a svn-checkout of my local vs-2015 project).
I have literally no idea on how to solve the problem. Can anyone help me with this?
|
Your code is made too complicated, you can simplify it to this:
template <typename T>
bool toNumber(std::string str, T& num)
{
return !!(std::istringstream { std::move(str) } >> num);
}
https://godbolt.org/z/Pq5xGdof5
Ok I've missed that you wish to avoid zero assignment in case of failure (what streams do by default):
template <typename T>
bool toNumber(std::string str, T& num)
{
T tmp;
std::istringstream stream{ std::move(str) };
if (stream >> tmp) {
num = tmp;
}
return !!stream;
}
https://godbolt.org/z/nErqn3YYG
|
74,305,853
| 74,306,215
|
Failing to generate X509 CSR with OpenSSL
|
I am trying to generate a signing request. Apparentely there is an error somewhere in the code (or UB most likelly) which leads to:
garbage output locally
returned code 139 on godbolt
#include <memory>
#include <stdexcept>
#include <string>
#include <iostream>
namespace {
std::string make_csr();
} // namespace
int main(int, char **) {
try {
std::cout << ::make_csr() << std::endl;
return 0;
}
catch (const std::exception &e)
{
std::cerr << "Failed with error: " << e.what() << std::endl;
return -1;
}
}
#include <openssl/aes.h>
#include <openssl/bn.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
namespace ssl_utils {
template <typename T> void free(T *);
template <typename T> T *make();
template <typename T> class raii_obj {
private:
struct _free {
void operator()(T *ptr) const { ssl_utils::free(ptr); }
};
public:
using type = T;
using ptr = std::unique_ptr<type, _free>;
static ptr make() { return ptr(ssl_utils::make<type>()); }
};
using raii_bignum = raii_obj<BIGNUM>;
using raii_evp_pkey = raii_obj<EVP_PKEY>;
using raii_x509_req = raii_obj<X509_REQ>;
} // namespace ssl_utils
namespace {
std::string make_csr() {
constexpr size_t privateKeyLength{2048};
auto pBignum = ssl_utils::raii_bignum::make();
auto pKey = ssl_utils::raii_evp_pkey::make();
RSA *rsa = RSA_new();
if (!(static_cast<bool>(pBignum) && //
static_cast<bool>(rsa) && //
BN_set_word(pBignum.get(), RSA_F4) &&
RSA_generate_key_ex(rsa, //
privateKeyLength, //
pBignum.get(), //
nullptr) &&
EVP_PKEY_assign_RSA(pKey.get(), rsa))) {
throw std::runtime_error("Failed to generate RSA key!");
}
auto pReq = ssl_utils::raii_x509_req::make();
X509_REQ_set_version(pReq.get(), 0L);
X509_REQ_set_pubkey(pReq.get(), pKey.get());
X509_NAME *const pName = X509_REQ_get_subject_name(pReq.get());
X509_NAME_add_entry_by_txt(
pName, LN_pkcs9_emailAddress, MBSTRING_UTF8,
reinterpret_cast<const unsigned char *>(
"dummy.mail@gmail.com"),
-1, -1, 0);
if (!X509_REQ_sign(pReq.get(), pKey.get(), EVP_md5()) ||
!X509_REQ_verify(pReq.get(), pKey.get()))
throw std::runtime_error("CSR signing failed!");
unsigned char *request = request;
const std::string::size_type reqSize =
i2d_X509_REQ(pReq.get(), &request);
std::string strReq{reinterpret_cast<char *>(request), reqSize};
// CRYPTO_free(request); // does not compile
return strReq;
}
}
namespace ssl_utils {
template <> BIGNUM *make() { return BN_new(); }
template <> void free(BIGNUM *ptr) { BN_free(ptr); }
template <> EVP_PKEY *make() { return EVP_PKEY_new(); }
template <> void free(EVP_PKEY *ptr) { EVP_PKEY_free(ptr); }
template <> X509_REQ *make() { return X509_REQ_new(); }
template <> void free(X509_REQ *ptr) { X509_REQ_free(ptr); }
} // namespace ssl_utils
When debugging on my local machine, I don't see any of the X509_REQ_sign, X509_REQ_verify or i2d_X509_REQ calls failing. So my first thought was that the console's encoding was to blame:
0�j0�R 0%1#0! *�H��
dummy.mail@gmail.com0�"0
*�H��
� 0�
� ��*��6�
�*x���~����V'U&�,+x�c|ϊ����t�!cjBS 3��pI�?�i�弒 s�8���2�r��N�f�T�sq�>Ն�0���#��Z�\�Td_�?im$m]�Ts�RW"�M���Xr��Z+r�J���Q$���,ɏ4��)8`R�����)ދAn��B�Di:W�������}
x(ʴ���v�&%�X����k}�P��U�7��ƀ{��l��O!<A��"I���R
�%�o!v�k�̳ � 0
*�H��
� J�V��K����Pj�u"���nX&yK��e�p��������/V��A��r����Р�c�s�ֶ�>�T4�7���5j������BF�s0D��f�-j�w�c �[:���5cf����0�u�`����&$�"�� ���?��dR��2��w ��v���}5qA�8�Rw�+���J��B��Y�n����Z�ۭ]gLt���gۿY��Q3B#k����bш�VWjN�5P�
���B��Ţ���۪�� ��
But then I checked the code at godbold and found out that it crashes at some point there.
I am using OpenSSL for MinGW-w64 from Msys2 package (version "1.1.1q").
|
The root issue is here, the typo:
unsigned char *request = request;
It is initialized with an unspecified value and should be
unsigned char *request = nullptr;
Otherwise i2d_X509_REQ tries to realloc the invalid pointer.
CRYPTO_free(request); // does not compile
should be
OPENSSL_free(request);
https://godbolt.org/z/ofnc3M9h1
|
74,306,531
| 74,306,740
|
Linked List: Moving a Node to Start of the Linked List(C++)
|
The question is to find the key in a linked list and if it is present then move the node containing key to the front
struct Node {
int data;
Node *next;
Node(int data, Node *next_node) {
this->data = data;
this->next = next_node;
}
};
void display(Node *head) {
Node *temp_head = head;
while(temp_head != NULL) {
std::cout << temp_head->data << " ";
temp_head = temp_head->next;
}
std::cout << '\n';
}
bool improvedSearch(Node *head, int key) {
Node *previous = NULL, *current = head;
while(current != NULL) {
if(current->data == key) {
if(previous == NULL) {
return true;
}
previous->next = current->next;
current->next = head;
head = current;
display(head); /////
return true;
}
previous = current;
current = current->next;
}
return false;
}
int main() {
Node e(5, NULL);
Node d(4, &e);
Node c(3, &d);
Node b(2, &c);
Node a(1, &b);
Node *head = &a;
improvedSearch(head, 3);
display(head); /////
return 0;
}
When I call display inside the improvedSearch(head, 3) it shows the output "3 1 2 4 5" but when I call the display inside main function the output is "1 2 4 5". It seems like link to node containing 3 gets lost. Why is this happening?
|
In improvedSearch(), you are passing in the head parameter by value, so a copy of the caller's head is made, and any new value assigned to the head parameter by improvedSearch() will be only to that copy and not reflected back to the caller. But, improvedSearch() still modifies the contents of the list, and upon exit the caller's head is still pointing at the old head node which is no longer the new head node, which is why it appears a node was lost.
To fix this, pass in the head parameter by reference instead:
bool improvedSearch(Node* &head, int key)
|
74,306,914
| 74,306,938
|
c++ std::string use overwrites values
|
What am I doing wrong here? Apparently aval is overwritten
when I call getbbb. Expected output is:
test A aval: "aaa"
test B aval: "aaa"
Actual output is:
test A aval: "aaa"
test B aval: "bbb"
File testb.c:
#include <string>
// g++ -o tempa testb.c && ./tempa
std::string getaaa() {
return std::string("aaa");
}
std::string getbbb() {
return std::string("bbb");
}
int main(
int argc, // num args, including pgm name
char * argv[]) // args
{
const char * aval = getaaa().c_str();
printf("test A aval: \"%s\"\n", aval);
getbbb();
printf("test B aval: \"%s\"\n", aval);
return 0;
}
|
const char * aval = getaaa().c_str(); leads to undefined behavior.
getaaa() returns a temporary string object that is destroyed when the full expression that created it is finished (ie, on the ;), which is after you have grabbed the string's data pointer. Thus, the pointer is left dangling, pointing at freed memory. Any subsequent reading from that pointer is undefined behavior.
Since the string object from getaaa() is destroyed and its data freed before getbbb() is called, getbbb() is allowed to reuse the same memory for its own string object. This is not guaranteed, but it is possible (and clearly the case in your situation).
To solve this, save the temporary string object from getaaa() to a local string variable before grabbing the pointer:
const string sval = getaaa();
const char * aval = sval.c_str();
printf("test A aval: \"%s\"\n", aval);
getbbb();
printf("test B aval: \"%s\"\n", aval);
|
74,307,601
| 74,307,937
|
Apple METAL C++ problem with MTL::CopyAllDevices();
|
I'm trying to get C++ code working with Metal.
I get the array of MTL:Device by calling
NS::Array *device_array = MTL::CopyAllDevices();
Next, I want to get the only element of the MTL::Device array by calling
MTL::Device *device = device_array->object(0);
I get an error:
Cannot initialize a variable of type 'MTL::Device *' with an rvalue of type 'NS::Object *'
Question:
how to get an MTL::Device object from NS::Array?
|
NS::Array just contains NS::Objects, it doesn't know what it contains, therefore by default .object(index) returns NS::Object* which is a base class of MTL::Device and therefore not automatically castable. Fortunately object is a template so you can just do:
MTL::Device *device = device_array->object<MTL::Device>(0);
to retrieve the object with the correct class.
Note that this is just implemented with a reinterpret_cast so there is no checking that you've actually used the correct class so use with care!
|
74,308,250
| 74,309,345
|
C++ How to pass array to a print function?
|
The program asks the user for a number of random numbers,
then gives a menu of what to do with the arrays.
I want to print the arrays to the standard output device.
How do I pass "baseArray[i]" and "copyArray[i]" to "arrayPrint(int arr[], int size)" ?
void randN() {
int n;
cout << "Enter a number (in the set of integers) of random numbers to generate. (e .g 1000)\n> ";
cin >> n;
int baseArray[n], copyArray[n];
time_t nTime;
srand((unsigned) time(&nTime));
cout << "Random numbers between 0 to 1000\n" << endl;
for (int i = n; i != 0; i--){
baseArray[i] = rand()%1000 + i;
copyArray[i] = baseArray[i];
}
cout << endl << endl;
pMenu();
}
void pMenu(){
int selectioN = 0;
cout << "Main Menu\n";
cout << "1 - Generate Random Array\n";
cout << "2 - Print The Original Array\n";
cout << "3 - Print The Copy Array\n";
cout << "4 - Exit program\n" << endl;
cout << "Selection >> ";
cin >> selectioN;
switch (selectioN) {
case 1:
randN();
break;
case 2:
arrayPrint(baseArray, 1000);
break;
case 3:
arrayPrint(copyArray, 1000);
break;
case 4:
pExit();
break;
}
}
void arrayPrint(int arr[], int size){
for (int i = 1000; i != 0; i--){
cout << arr[i] << " ";
}
}
I tried to make separate functions for menu, arrayPrint, and the random number generator.
I tried to call the function in the menu to print each array.
When I build, I get the error that baseArray and copyArray are not declared in this scope, which I understand the meaning of that already, but how do I declare them, do I need to dereference the arrays?.
|
I made the local array variables into global variables.
I also updated the random number generator based off of this:
std::uniform_int_distribution
|
74,308,262
| 74,308,772
|
Why do partial and full C++ template specializations, that look almost the same, produce different results?
|
I haven't written many C++ templates till recently, but I'm trying to take a deep dive into them. Fixing one developer's code I managed to produce some compiler behavior that I can't explain. Here is the simplified program. ( When I try to simplify more, I lose that "strange" behavior). Let's think of some class Depender, which is a parameter of template struct Dependency. Depender can depend on the List of Dependees. I have some macros that can produce specializations of the Dependency template. Dots in the following code block stand for the possible macro expansion. I have a forward-declared MainDependee before dots, and MainDependee's definition after dots.
#include <type_traits>
template <typename T, typename = void>
struct IsCompleteType : std::false_type
{};
template <typename T>
struct IsCompleteType<T, std::enable_if_t<( sizeof( T ) > 0 )>> : std::true_type
{};
template<template<typename...> class List, typename Dependee>
struct DependencyInternal
{
using Type = std::conditional_t<IsCompleteType<Dependee>::value, Dependee, Dependee>;
};
template<typename... Ts> class StubList;
class MainDependee; // forward declaration
class MainDepender
{};
template<template<typename...> class List, typename Depender>
struct Dependency;
....... //here is the specialization
class MainDependee {};
int main()
{
Dependency<StubList, MainDepender> a;
}
When the dots are replaced with
template<template<typename... Us> class List>
struct Dependency<List, MainDepender>
{
using Type = typename DependencyInternal<List, MainDependee>::Type;
};
then in main I get IsCompleteType<MainDependee>::value == true.
But when the dots are replaced with
template<>
struct Dependency<StubList, MainDepender>
{
using Type = typename DependencyInternal<StubList, MainDependee>::Type;
};
then IsCompleteType<MainDependee>::value == false.
Please tell me, what rule describes the difference between these options?
Try the code yourself
|
An explicit (full) specialization is not itself a templated entity and all name lookup etc., as well as ODR, is done for it as if it wasn't a template. MainDependee is not complete at the point you wrote it and therefore IsCompleteType<MainDependee> is inherited from std::false_type at this point.
A partial specialization is itself a templated entity and will follow the rules for templates. In particular a definition will be instantiated from the partial specialization only when and where an instantiation is required. In this case the instantiation for Dependency<StubList, MainDepender> has its point of instantiation directly before main where MainDependee is complete. Only there Type is computed (because the right-hand side is dependent on the template parameter) and IsCompleteType<MainDependee> instantiated, so that it will be inherited from std::true_type.
Note that class template specializations are instantiated only once per translation unit. If you use Dependency<StubList, MainDepender>::value multiple times in a translation unit, it will always result in the same value, the one which would be correct at the first point from where instantiation is required.
Furthermore, if Dependency<StubList, MainDepender>::value or IsCompleteType<MainDependee> would have different values in different translation units because of different relative placement of MainDependee, your program will be IFNDR (ill-formed, no diagnostic required), effectively meaning it will have undefined behavior.
It is not possible to use a type trait like this to safely check whether a type is complete. For the same reason there is no such trait in the standard library.
|
74,308,519
| 74,308,569
|
How do i make different responses to different user inputs?
|
I'm a beginner, so please excuse my silly mistakes.
I'm trying to get a specific output when I input a specific name using strings, but I keep getting an error that my name wasn't declared in the scope. I also want to be able to add different responses for different inputs.
I tried looking up how to use strings, and I tried all sorts of combinations, but I'm still confused as to what I did wrong.
I'm sorry if this doesn't make sense, I'm just really bad at explaining things.
#include <iostream>
#include <cmath>
#include <string>
int main() {
std::string firstname;
std::cout << "please state your name. \n";
std::cout << firstname;
std::cin >> firstname;
if (firstname == leo) {
std::cout << "oh, you.";
}
return 0;
}
|
First, std::cout << firstname; is a no-op since firstname is empty at that point.
Second, there is no name in your code. Is the error referring to leo? That should be wrapped in double-quotes since you meant it to be a string literal, not a variable.
Try something more like this:
#include <iostream>
#include <string>
int main() {
std::string firstname;
std::cout << "please state your name. \n";
std::cin >> firstname;
if (firstname == "leo") {
std::cout << "oh, you.";
}
else {
std::cout << "hello, " << firstname;
}
return 0;
}
|
74,308,720
| 74,308,786
|
Binary tree: root remains NULL after addition
|
The problem is my root stays NULL when I need it to change after the first call of my addContact function.
I have tried pointer to pointer but got an access error... This 0x28... Is all I remember about the error. I have also tried using *& in the parameter of my addContact function but to no avail. What I will show in code is what I thought would fix it but my logic is flawed obviously. Any help would be much appreciated!
This is in my header file.
struct Transaction {
std::string ID;
std::string lName;
std::string fName;
std::string pNum;
std::string eMail;
std::string address[7];
};
struct Node {
Transaction data;
Node* left;
Node* right;
};
Node* addHelper(Transaction data) {
Node* newNode = new Node();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
Node* addContact(Node* root, Transaction data) {
if (root == NULL) {
std::cout << "Checking to see if root stays NULL" << std::endl;
root = addHelper(data);
}
else if (data.lName <= root->data.lName) {
root->left = addContact(root->left, data);
}
else {
root->right = addContact(root->right, data);
}
return root;
}
This is in my Main file.
#include <iostream>
#include <fstream>
#include "Header.h"
using namespace std;
int main() {
ifstream file; file.open("bt.txt");
Transaction inputArray[3];
for (int i = 0; i < 3; i++) {
file >> inputArray[i].ID >> inputArray[i].lName >> inputArray[i].fName >> inputArray[i].pNum >> inputArray[i].eMail;
for (int j = 0; j < 7; j++) {
file >> inputArray[i].address[j];
}
}
Node* root = NULL;
root = addContact(root, inputArray[0]);
root = addContact(root, inputArray[1]);
root = addContact(root, inputArray[2]);
}
|
In addContact you have modified the root parameter, but that is local to the function and has no bearing on the value passed in.
Sticking with raw pointers, you may want to pass in a pointer to a pointer, so you can modify the pointer you're pointing to.
Node* addContact(Node** root, Transaction data) {
if (*root == NULL) {
std::cout << "Checking to see if root stays NULL" << std::endl;
*root = addHelper(data);
}
else if (data.lName <= (*root)->data.lName) {
(*root)->left = addContact(&(*root)->left, data);
}
else {
(*root)->right = addContact(&(*root)->right, data);
}
return *root;
}
As noted in comments, you can make addHelper a constructor for Node.
struct Node {
Transaction data;
Node* left;
Node* right;
Node(Transaction data) : data(data), left(nullptr), right(nullptr) { }
};
|
74,308,933
| 74,309,050
|
Address of static data member
|
Why C++ doesn't allow taking the address of a static data member when the data member is initialize within the class and doesn't have an out-of-class definition? How is the storage allocated for static member in this case?
The below minimum program demonstrate the issue.
#include <iostream>
class Test {
public:
static const int a = 99; // how is the storage allocated for Test::a??
};
// const int Test::a;
int main() {
std::cout << Test::a << '\n'; // OK, print 99
const int* ptr = &Test::a; // Linker error, undefined reference to Test::a
}
If I uncomment the line const int Test::a, then the program works fine.
|
This line is a declaration:
static const int a = 99;
It is not a definition. For storage to be allocated, you need a definition. That's where your commented line comes into play.
You can use Test::a even if it has no definition because it is treated as a compile-time constant. In general, a static const T variable (where T is a trivial type) must be usable in a constant expression as soon as it is constant-initialized.
Note that you can get both behaviors (compile-time constant and variable with an address) at the same time:
class Test {
public:
static const int a = 99;
};
const int Test::a;
template<int i>
struct Templated {};
int main() {
const int* ptr = &Test::a;
Templated<Test::a> a;
}
Demo
And to illustrate the constant-initialization point:
class Test {
public:
static const int a;
};
template<int i>
struct Templated {};
// does not compile because Test::a is *not yet* usable in a constant expression
Templated<Test::a> global;
const int Test::a = 99;
int main() {
const int* ptr = &Test::a;
Templated<Test::a> a;
}
Demo
|
74,309,235
| 74,309,609
|
How to define equivalent rule for non type template arg
|
After some time of figuring out my question I have found it's really fascinating how compiler can deduce template arguments from set of "tags" (non-type template args). But it looks like the compiler only understands "byte by byte" equality rule.
What I mean is this code:
struct S1 {
constexpr S1(int v) : _v(v)
{};
constexpr bool operator == (const S1& other) { return true;}
int _v;
};
template <S1 Tag, typename ValueType>
struct TagedValue { ValueType value; };
struct Test : TagedValue<S1{0}, int>, TagedValue<S1{1}, double> {};
template <S1 Idx, typename T>
auto& get(TagedValue<Idx, T>& test) {
return test.value;
}
int main()
{
Test test;
get<S1{1}>(test); // Still compiles, even though S1{0} == S1{1}
static_assert(S1{0} == S1{1});
}
As you can see I have defined my own operator == which basically says: "any two instances are equal". But it looks like in order to deduce T in get function the compiler still checks whether or not the actual content of the struct is the same. That is, for the purpose of type deduction S1{0} != S2{1}, even though S1{0} == S2{1} from "C++ point of view".
My question is: Is there any way I can redefine that "type deduction equality rule"?
UPD: To make it probably more clear, if I replace this line
struct Test : TagedValue<S1{0}, int>, TagedValue<S1{1}, double> {};
with
struct Test : TagedValue<S1{1}, int>, TagedValue<S1{1}, double> {};
the compiler gives an error, complaining about ambiguty.
|
Template parameter deduction, and other template-related things, use the concept of type equivalence. The parts relevant to your question are these:
temp.type/1 Two template-ids are the same if
...
(1.3) - their corresponding non-type template-arguments are template-argument-equivalent (see below) after conversion to the type of the template-parameter...
temp.type/2 Two values are template-argument-equivalent if they are of the same type and
...
(2.10) - they are of class type and their corresponding direct subobjects and reference members are template-argument-equivalent.
Roughly, it's member-wise equality. No, you cannot override it.
|
74,309,326
| 74,310,178
|
Print backwards all the positive even integers starting with 100 using loop
|
How do I print only the even integers using a loop?
so far I have:
for (int i = 100; i > 0; i--)
{
cout << i << ", ";
}
which prints all the numbers, even and odd. How do I print just the even numbers?
|
Sigh. All the comments (and the close vote) seem hung up on checking whether an integer is even. That's not needed; instead of skipping odd values, don't generate them in the first place:
for (int i = 100; i > 0; i-=2)
|
74,309,382
| 74,309,666
|
cmake: target_link_libraries - /usr/bin/ld: cannot find X No such file or directory
|
I'm trying to include this library in my project:
https://github.com/kuafuwang/LspCpp.git
I'm using FetchContent which succesfully populates _deps/lspcpp-build, _deps/lspcpp-src, _deps/lspcpp-subbuild:
FetchContent_Declare(
lspcpp
GIT_REPOSITORY https://github.com/kuafuwang/LspCpp.git
)
FetchContent_GetProperties(lspcpp)
if(NOT lspcpp_POPULATED)
FetchContent_Populate(lspcpp)
endif()
I define my executable:
add_executable(myApp
foo.cpp
bar.cpp
...
)
And try to link it:
target_include_directories(myApp lspcpp)
target_link_libraries(myApp lspcpp)
This produces this error:
/usr/bin/ld: cannot find -llspcpp: No such file or directory
|
You are missing a step for FetchContent, to build the library.
FetchContent_Declare(
lspcpp
GIT_REPOSITORY https://github.com/kuafuwang/LspCpp.git
)
FetchContent_GetProperties(lspcpp)
if(NOT lspcpp_POPULATED)
FetchContent_Populate(lspcpp)
add_subdirectory(${lspcpp_SOURCE_DIR} ${lspcpp_BINARY_DIR}) # add this line
endif()
|
74,309,472
| 74,309,935
|
SendMessage COPYDATASTRUCT wrong string when recive in delphi
|
I send the following c++ application request:
string data_to_send = "Hello World";
PCSTR lpszString = data_to_send.c_str();
COPYDATASTRUCT cds;
cds.dwData = 0; // can be anything
cds.cbData = sizeof(TCHAR) * (data_to_send.size());
cds.lpData = &lpszString;
cout << lpszString << endl;
SendMessage(Output, WM_COPYDATA, (WPARAM)Output, (LPARAM)(PVOID)&cds);
I get the structure using the following code in Delphi
var
p : PCopyDataStruct;
s : UTF8String;
begin
p := PCopyDataStruct(Message.lParam);
if (p <> nil) then
begin
SetString(s, PAnsiChar(p^.lpData), p^.cbData);
ShowMessage(s);
end else
inherited;
end;
The string looks wrong.
In the debugger, it is equal to the following
'l'#$FE#$F6#2'Hello World'#0#$10#3#$88'u'#$B#0
We see 22 bytes with an extra 4 bytes before the message.
If we use CHAR instead of TCHAR, then we see 11 bytes, but again with an offset of 4 bytes
#$18#$F9#$1B#3'Hello W'
Please, help!!!
UPDATE:
Thanks to Remy Lebeau for his help, his code does everything as it was originally intended and David Heffernan for the correct remark! They saved me. Here is the working code.
|
On the C++ side:
cds.dwData should not be 0. Use a more unique value, such as the result of calling RegisterWindowMessage(). Many apps, and even the VCL internally, use WM_COPYDATA for different purposes, so you don't want to get confused with someone else's message by mistake.
sizeof(TCHAR) should be sizeof(char) instead (or omitted entirely, since sizeof(char) is always 1).
cds.lpData = &lpszString; needs to be cds.lpData = lpszString; instead. You are sending the address of the lpszString variable itself, not the address of the character data it points at. That is why you are seeing garbage on the other end - you are seeing random bytes from the call stack where lpszString resides, which in your case includes the std::string object (whose internal members happen to include a Short-String-Optimization buffer, which is why you are also seeing your characters, too).
On the Delphi side:
you should validate p^.dwData is your unique number before processing the message any further. If the number does not match what you are expecting, pass the message to the inherited handler and move on.
UTF8String should be AnsiString, unless the sender's std::string is actually UTF-8 encoded.
Try this:
const UINT uMyDataID = RegisterWindowMessage(TEXT("MyDataID"));
...
if (uMyDataID != 0)
{
string data_to_send = u8"Hello World";
COPYDATASTRUCT cds;
cds.dwData = uMyDataID;
cds.cbData = sizeof(char) * data_to_send.size();
cds.lpData = const_cast<char*>(data_to_send.c_str());
// or: cds.lpData = data_to_send.data(); in C++17 and later
SendMessage(Output, WM_COPYDATA, reinterpret_cast<WPARAM>(Output), reinterpret_cast<LPARAM>(&cds));
}
var
uMyDataID: UINT = 0;
...
procedure TMyForm.WMCopyData(var Message: TMessage);
var
p : PCopyDataStruct;
s : UTF8String;
begin
p := PCopyDataStruct(Message.lParam);
if (uMyDataID <> 0) and (p <> nil) and (p^.dwData = uMyDataID) then
begin
SetString(s, PAnsiChar(p^.lpData), p^.cbData);
ShowMessage(s);
end else
inherited;
end;
...
initialization
uMyDataID := RegisterWindowMessage('MyDataID');
|
74,309,702
| 74,310,210
|
Merge several linked lists (smth with memory)
|
I've made my own linked list and now I am trying to implement function which will merge all lists. However, unfortunately I get this error:
"linkedList(28488,0x102a88580) malloc: *** error for object 0x600003a70010: pointer being freed was not allocated
linkedList(28488,0x102a88580) malloc: *** set a breakpoint in malloc_error_break to debug"
I suppose that problem is in the main function, when I create a list in for-loop. I tried to make a new node using new operator and then make a list from this node, error message disappeared but program didn't work still.
Here is the input:
4
1--->4--->5
1--->3--->4
2--->6
1
Here is the output:
1--->1--->1--->2--->3--->4--->4--->5--->6
Here is the code:
struct Node
{
int val;
Node* next;
Node(){}
Node(int x) : val(x), next(nullptr){}
};
struct List
{
List(Node* node) : head(node){}
List() : head(nullptr){}
~List();
void clear();
void push_back(int key);
void print();
Node* head;
};
void List::push_back(int val)
{
Node* newNode = new Node(val);
Node* cur = head;
if (head != nullptr)
{
while(cur->next != nullptr)
{
cur = cur->next;
}
cur->next = newNode;
}
else
{
head = newNode;
}
}
void List::print()
{
Node* cur = head;
while(cur != nullptr)
{
std::cout << cur->val;
if (cur->next != nullptr)
{
std::cout << "--->";
}
cur = cur->next;
}
}
void List::clear()
{
Node* cur = head;
while (cur != nullptr)
{
Node* a = cur;
cur = cur->next;
delete a;
}
}
List::~List()
{
clear();
}
Node* merge(Node* nodeFirst, Node* nodeSecond)
{
//function to merge two lists
if (!nodeFirst)
{
return nodeSecond;
}
if (!nodeSecond)
{
return nodeFirst;
}
if (nodeFirst->val <= nodeSecond->val)
{
nodeFirst->next = merge(nodeFirst->next, nodeSecond);
return nodeFirst;
}
else
{
nodeSecond->next = merge(nodeSecond->next, nodeFirst);
return nodeSecond;
}
}
Node* mergeAll(std::vector<List>& vecOfLists)
{
Node* answer = vecOfLists[0].head;
for (int i = 1; i < vecOfLists.size(); ++i)
{
answer = merge(answer, vecOfLists.at(i).head);
vecOfLists.at(i).clear();
}
return answer;
}
std::vector<int> getNums(const std::string& s, std::vector<int>& numbers)
{
size_t num_start = 0, num_end = 0;
const std::string arrow = "--->";
while (num_end < s.size())
{
num_end = s.find(arrow, num_start);
if (num_end == std::string::npos)
{
num_end = s.size();
}
numbers.push_back(std::stoi(s.substr(num_start, num_end - num_start)));
num_start = num_end + arrow.size();
}
return numbers;
}
List& makeList(List& list, const std::vector<int>& nums)
{
for (const int& x : nums)
{
list.push_back(x);
}
return list;
}
int main()
{
int k = 0;
std::cin >> k;
std::vector<List> vecOfLists;
for (int i = 0; i < k; ++i)
{
std::string s;
std::cin >> s;
std::vector<int> nums;
getNums(s, nums);
List list;
makeList(list, nums);
vecOfLists.push_back(list);
}
List list(mergeAll(vecOfLists));
list.print();
}
|
issue is here
List list;
makeList(list, nums);
vecOfLists.push_back(list);
list will be destructed after that push_back and hence delete all its allocated nodes, but then when you exit main the destructor is called again for the copy of List head in that vector.
YOu need to make the copy operation (used by the vector push_back) smarter
|
74,309,802
| 74,309,993
|
Compile time hints/warnings on struct changes
|
I have a basic POD struct with some fields
struct A{
int a,
int b,
};
The nature of my use case requires that these fields change every so often (like 1-2 months, regular but not often). This means that I want to check the field usages of the struct after the changes to make sure everything is still fine.
The compiler checks that all field usages are valid, something like a.c will fail at compile time.
However, some of my functions should access and handle ALL of the fields of A. So while the compiler verifies that all usages are valid, it doesn't validate that all the fields are used.
This work/checking must be done manually (if there is a way to do this at compile time, please enlighten me). So our current design tries to make this as easy as possible. We grouped most of the relevant functions into one folder/library so we could check over them in one place. However, some usages are embedded in private class functions that would honestly be more of a pain to refactor out into the common lib than the benefits it brings.
It's reasonable to just rely on documentation saying "Hey, after changing struct A, check the function foo in class FooThing". But I'm looking to see if we can get some type of compile time warnings.
My idea was to basically drop a static_assert next each relevant function that would check the size of A. Most changes should change the size, so an unchanged static_assert would fail at compile time, pointing me to the general area of the function. Then I could just change the function and the assert.
So besides the function foo for example, I would have something like static_assert(sizeof(A) == 16) or whatever size. This isn't foolproof, as it's possible that changes to struct might not change the total size, but I'm not looking for something really rigorous here, just something that could be helpful 90% of the time.
The main reason why this doesn't work for me is that int and other data types don't have a specified size from the standard. This is a problem for me since my project is cross platform.
In short, I am looking for a way to signal at compile time to check certain functions after a struct's definition has been changed.
|
One possibility is to put a version number into the struct itself, like so:
struct A{
int a;
int b;
static constexpr int major_version = 1;
};
Then, in calling code, you place assertions that check the value of the major version:
void doSomething(A a)
{
static_assert(A::major_version == 1, "Unexpected A major version");
// Do something with a
}
Then, any time you make an update to A that you think merits re-inspection of all calling code, you increment A::major_version, and then the static_assert will fire anywhere you haven't changed it.
|
74,310,316
| 74,310,407
|
Using variables from a class's constructor in one of its member functions?
|
I'm learning C++ and I want to know if there is a way you can use variables defined in a class's constructor in a member function. I've tried looking online and in my textbook but I can't find a definitive answer. For example:
class Item {
public:
Item(std::string str) {
std::string text = str;
int pos = -1;
}
void increment() {
// how would I reference pos here?
pos++;
}
};
Thanks in advance!
|
I want to know if there is a way you can use variables defined in a class's constructor in a member function.
No, you can't. Variables defined in the constructor goes out of scope at the end of the constructor.
The normal way is to initialize member variables in the constructor. These can then be accessed in the member functions:
class Item {
public:
Item(std::string str) : // colon starts the member initializer list
text(std::move(str)),
pos{-1}
{
// empty constructor body
}
void increment() {
pos++; // now you can access `pos`
}
private:
// member variables
std::string text;
int pos;
};
|
74,310,514
| 74,310,596
|
How to create the instance of a concrete implementation of a class in C++ as in Java?
|
Maybe it's a little weird question, but: I'm not so much familiar with C++.
Let's say we have an abstract class A and a class B that extends it:
abstract class A {
abstract void foo();
}
class B extends A {
@Override
void foo() {
// . . .
}
}
Then, in the Test class, we can create an instance of B this way:
class Test {
A a = new B();
}
Can I do something like this in C++?
Because, when I do the same in C++, I receive something like this:
(I have an abstract class Customer that's being extended by other class. There's being performed smth like this Customer* customer = new OnlineCustomer();)
|
In C++ you can't construct an abstract class, but you can make a pointer to an abstract class. Here's a direct translation of your code to C++:
#include <iostream>
struct A // structs are classes that are default public
{
// having at least one method be
// "= 0" flags the class as abstract:
virtual void foo() = 0;
virtual ~A() = default;
};
struct B : A
{
void foo() override
{
std::cout << "Hello World" << std::endl;
}
};
int main()
{
// Test:
// (in C++ not everything is about classes!)
// Where 'a' OWNS the data:
A* a1 = new B;
a1->foo();
delete a1;
// Where 'a' REFERS to the data:
B b;
A* a2 = &b;
a2->foo();
}
demo
Note that where Java is all about OOP and inheritance, in C++ OOP is just one of the tools in the tool box, and inheritance - although it has its place - is often seen as causing more problems than it solves (often templates or functional programming or composition would do better).
|
74,310,697
| 74,310,728
|
C++ undefined behavior with too many heap pointer deletions
|
I wrote a program to create a linked list, and I got undefined behavior (or I assume I did, given the program just stopped without any error) when I increased the size of the list to a certain degree and, critically, attempted to delete it (through ending its scope). A basic version of the code is below:
#include <iostream>
#include <memory>
template<typename T> struct Nodeptr;
template<class T>
struct Node {
Nodeptr<T> next;
T data;
Node(const T& data) : data(data) { }
};
template<class T>
struct Nodeptr : public std::shared_ptr<Node<T>> {
Nodeptr() : std::shared_ptr<Node<T>>(nullptr) { }
Nodeptr(const T& data) : std::shared_ptr<Node<T>>(new Node<T>(data)) { }
};
template<class T>
struct LinkedList {
Nodeptr<T> head;
void prepend(const T& data) {
auto new_head = Nodeptr<T>(data);
new_head->next = head;
head = new_head;
}
};
int main() {
int iterations = 10000;
{
LinkedList<float> ls;
std::cout << "START\n";
for(float k = 0.0f; k < iterations; k++) {
ls.prepend(k);
}
std::cout << "COMPLETE\n";
}
std::cout << "DONE\n";
return 0;
}
Right now, when the code is run, START and COMPLETE are printed, while DONE is not. The program exits prior without an error (for some reason).
When I decrease the variable to, say, 5000 instead of 10000, it works just fine and DONE is printed. When I delete the curly braces around the LinkedList declaration/testing block (taking it out its smaller scope, causing it NOT to be deleted before DONE is printed), then everything works fine and DONE is printed. Therefore, the error must be arising because of the deletion process, and specifically because of the volume of things being deleted. There is, however, no error message telling me that there is no more space left in the heap, and 10000 floats seems like awfully little to be filling up the heap anyhow. Any help would be appreciated!
Solved! It now works directly off of heap pointers, and I changed Node's destructor to prevent recursive calls to it:
~Node() {
if(!next) return;
Node* ptr = next;
Node* temp = nullptr;
while(ptr) {
temp = ptr->next;
ptr->next = nullptr;
delete ptr;
ptr = temp;
}
}
|
It is a stack overflow caused by recursive destructor calls.
This is a common issue with smart pointers one should be aware of when writing any deeply-nested data structure.
You need to an explicit destructor for Node removing elements iteratively by reseting the smart pointers starting from the tail of the list. Also follow the rule-of-3/5 and do the same for all other operations that might destroy nodes recursively as well.
Because this is essentially rewriting all object destruction it does however make use of smart pointers in the first place somewhat questionable, although there is still some benefit in preventing double delete (and leak) mistakes. Therefore it is common to simply not use smart pointers in such a situation at all and instead fall back to raw pointers and manual lifetime management for the data structure's nodes.
Also, there is no need to use std::shared_ptr here in any case. There is only one owner per node. It should be std::unique_ptr. std::shared_ptr has a very significant performance impact and also has the issue of potentially causing leaks if circular references are formed (whether intentionally or not).
I also don't see any point in having Nodeptr as a separate class. It seems to be used to just be an alias for std::make_shared<Node>, which can be achieved by just using a function instead. Especially inheriting from a standard library smart pointer seems dubious. If at all I would use composition instead.
|
74,311,243
| 74,311,448
|
How to avoid duplicated code when using recursive parameter packs C++
|
How do you avoid code duplication when using varadic parameters in c++? Notice that I'm using templates recursively to achieve my goals, therefore I need some base cases and a recursive case. This creates a lot of code duplication, are there ways I could reduce this duplication?
Below, an example is provided of code that creates an arbitrary tensor (N dimensional array).
It's working fine but there's too much duplication. How can I avoid writing duplicated code when using template parameter packs recursively like this?
#include <cstddef>
#include <array>
#include <iostream>
template<typename T, std::size_t...>
class Tensor;
template<typename T, std::size_t N>
class Tensor<T, N> {
using Type = std::array<T, N>;
Type data;
public:
Tensor()
{
zero();
}
void zero()
{
fill(0);
}
Type::iterator begin() { return data.begin(); }
Type::iterator end() { return data.end(); }
void fill(T value)
{
std::fill(data.begin(), data.end(), value);
}
void print() const
{
std::cout << "[";
for(const auto& v : data)
{
std::cout << v << ",";
}
std::cout << "]";
}
};
template<typename T, std::size_t N, std::size_t M>
class Tensor<T, N, M>
{
using Type = std::array<Tensor<T, M>, N>;
Type data;
public:
Tensor()
{
zero();
}
void zero()
{
fill(0);
}
Type::iterator begin() { return data.begin(); }
Type::iterator end() { return data.end(); }
void fill(T value)
{
for(auto& v: data) {
std::fill(v.begin(), v.end(), value);
}
}
void print() const
{
std::cout << "[";
for(const auto& v : data)
{
v.print();
std::cout << ",";
}
std::cout << "]";
}
};
template<typename T, std::size_t N, std::size_t... M>
class Tensor<T, N, M...>
{
using Type = std::array<Tensor<T, M...>, N>;
Type data;
public:
Type::iterator begin() { return data.begin(); }
Type::iterator end() { return data.end(); }
Tensor()
{
zero();
}
void zero()
{
fill(0);
}
void fill(T value)
{
for(auto& v: data) {
v.fill(value);
}
}
void print() const
{
std::cout << "[";
for(const auto& v : data)
{
v.print();
std::cout << ",";
}
std::cout << "]";
}
};
|
The only difference between a single-dimension tensor and a multiple-dimension tensor is the type of std::array, T for single and Tensor<T, M...> for another.
template<typename T, std::size_t N, std::size_t... M>
class Tensor<T, N, M...> {
using InnerT = std::conditional_t<(sizeof...(M) > 0),
Tensor<T, M...>,
T>;
using Type = std::array<InnerT, N>;
Type data;
}
Then, use if constexpr to distinguish single-dimension case,
void fill(T value)
{
if constexpr(sizeof...(M) > 0) {
for(auto& v: data) {
v.fill(value);
}
} else {
std::fill(data.begin(), data.end(), value);
}
}
void print() const
{
std::cout << "[";
for(const auto& v : data)
{
if constexpr(sizeof...(M) > 0) {
v.print();
std::cout << ",";
} else {
std::cout << v << ",";
}
}
std::cout << "]";
}
Demo
|
74,311,733
| 74,311,785
|
C++ Sum parameter pack into a template argument
|
How can I sum all the std::size_t parameters passed through the template into one std::size_t value that will define the size of the array.
template<typename T, std::size_t... N>
class Example {
std::array<T, N + ...> data; // std::array<T, sum of all N...>
};
|
You almost have it. You need to use a fold expression for this which is the same syntax, just surrounded with (). That gives you
template<typename T, std::size_t... N>
struct Example {
std::array<T, (N + ...)> data; // std::array<T, sum of all N...>
};
And in this example you'll get an error that tells you the array member has the size of the sum of the parameters.
template<typename T, std::size_t... N>
struct Example {
std::array<T, (N + ...)> data; // std::array<T, sum of all N...>
};
template <typename T>
struct get_type;
int main()
{
Example<int, 1, 2, 3> ex;
get_type<decltype(ex.data)>{};
}
Error:
main.cpp: In function 'int main()':
main.cpp:27:33: error: invalid use of incomplete type 'struct get_type<std::array<int, 6> >'
27 | get_type<decltype(ex.data)>{};
| ^
main.cpp:22:8: note: declaration of 'struct get_type<std::array<int, 6> >'
22 | struct get_type; ^
| ^~~~~~~~ |
// here you see 1 + 2 + 3 == 6 --------+
live example
|
74,311,777
| 74,311,805
|
When is it ever useful to use negative indexing of a C array?
|
C arrays allow for negative indexing, but I can't think of a use for that, seeing that you'll never have an element at a negative index.
Sure, you can do this:
struct Foo {
int arr1[3] = { 1, 2, 3 };
int arr2[3] = { 4, 5, 6 };
};
int main() {
Foo foo;
std::cout << foo.arr2[-2] << std::endl; //output is 2
}
But why would you ever want to do something like that? In any case, when is negative indexing of an array necessary, and in what domains would you be doing it in?
|
Remember that when you index an array, you get the element at index N which is the element at &array[0] + sizeof(array[0]) * N.
Suppose you have this code:
#include <stdio.h>
int main()
{
int a[5] = {5, 2, 7, 4, 3};
int* b = &a[2];
printf("%d", b[-1]); // prints 2
}
|
74,312,356
| 74,312,455
|
C++20 How to get the last element of a parameter pack of std::size_t
|
I've seen many answers online such as this one, but they do not seem to work when the parameter pack is of std::size_t.
template <typename ...Ts>
struct select_last
{
using type = typename decltype((std::type_identity<Ts>{}, ...))::type;
};
template<std::size_t... N>
class Example {
private:
using type = select_last<int, double>::type; // works
using size_t_type = select_last<size_t... N>::type; // doesn't work
};
How can I get the last element of a parameter pack of type std::size_t?
|
The template<std::size_t... N> is based on a non-type template parameter, so you cannot extract the type (or more precisely, there is no sense in trying to extract the type - I can just tell you it is std::size_t!), you may however extract the value, into a static constexpr.
Here is the proposed code:
template<std::size_t... N>
struct Last {
static constexpr std::size_t val = (N, ...); // take the last
};
int main() {
std::cout << Last<1, 2, 3, 99>::val; // 99
}
If you want, you can actually have it work for any type:
template<auto... N>
struct Last {
static constexpr auto val = (N, ...); // take the last
};
|
74,312,956
| 74,313,430
|
Dynamically allocate a vector using new keyword
|
I was wondering if it is possible to dynamically allocate a vector using new keyword, similar to an array.
what I mean is this:
vector<int> *vptr = new vector<int>;
I could not find proper reference about this problem over the internet.
I would like to know what the below statement means. Both are valid syntax.
Also how to dereference the pointer here.
vector<int> *vptr = new vector<int>[10];
vector<int> *vptr1 = new vector<int>(2,5);
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
// v is pointer toward a vector<int>
vector<int> *v = new vector<int>();
// So we should use '->' to dereference
// and use the method push_back
v->push_back(1);
v->push_back(2);
v->push_back(3);
for (auto i = 0u; i < v->size(); i++) {
// we are using at method to access
// elements as it is more readable
// than (*v)[i]
cout << v->at(i) << endl;
}
// v1 is an array of vector<int>
vector<int> *v1 = new vector<int>[10];
for (int i = 0; i < 10; i++) {
// we access to the ith vector with
// the [] operator same way we deal
// with other arrays. v[i] is of type
// vector so we use directly the push_back method
v1[i].push_back(i);
}
for (int i = 0; i < 10; i++) {
cout << v1[i][0] << endl;
}
delete [] v1;
// same as v
vector<int> *v2 = new vector<int>(2, 3);
for (auto i = 0u; i < v2->size(); i++) {
cout << v2->at(i) << endl;
}
return 0;
}
|
74,313,180
| 74,313,261
|
How to prevent floating-point being implicitly converted to integral value at function call in c++?
|
How to prevent floating-point being implicitly converted to integral value at function call?
#include <iostream>
void fn(int x) {
std::cout<<"fn("<<x<<")\n";
}
int main() {
std::cout<<"Hello, this is 301014 :)\n";
fn(2);
fn(3.5);
return 0;
}
Here the outputs are 2 and 3 respectively.
I am compiling with g++ -std=c++11 31014.cpp -o 31014 -v. And there is no mention of 3.5 being converted to 3.
Is there a way to prevent, or atleast detect, this?
Kindly help me out, please.
|
There are multiple ways to handle this in c++11.
Method 1: You SFINAE the function template fn by using std::enable_if.
template<typename T>
typename std::enable_if<std::is_same<T, int>::value>::type fn(T x) {
std::cout << "fn(" << x << ")\n";
}
int main() {
std::cout << "Hello, this is 301014 :)\n";
fn(2); // works
// fn(3.5); // won't work;
}
Demo
Method 2: Alternatively, delete the functions using =delete, which shouldn't take place in
template deduction.
void fn(int x) { // #1
std::cout << "fn(" << x << ")\n";
}
template<typename T> void fn(T) = delete; // #2
int main() {
std::cout << "Hello, this is 301014 :)\n";
fn(2); // works using #1
// fn(3.5); // won't work since it uses #2
}
Demo
|
74,313,313
| 74,313,489
|
To transform std::bind to std::function?
|
See the code below
queue<function<void()> > tasks;
void add_job(function<void(void*)> func, void* arg) {
function<void()> f = bind(func, arg)();
tasks.push( f );
}
func is the function I want to add to the tasks which has argument is arg.
How can I do to use std::bind to bind its argument so that it can be assigned to the object of std::function<void()>?
|
How can I do to use std::bind to bind its argument so that it can be assigned to the object of function<void()>?
The std::bind returns an unspecified callable object, which can be stored in the std::function directly. Therefore you required only
function<void()> f = bind(func, arg); // no need to invoke the callable object
tasks.push( f );
However, I would recommend using lambdas (since C++11) instead of std::bind.
Secondly, having global variables are also not a good practice. I would propose the following example code. Let the compiler deduce the type of the passed functions and their (variadic) arguments (function-template).
template<typename Callable, typename... Args>
void add_job(Callable&& func, Args const&... args)
{
// statically local to the function
static std::queue<std::function<void()>> tasks;
// bind the arguments to the func and push to queue
tasks.push([=] { return func(args...); });
}
void fun1(){}
void fun2(int){}
int main()
{
add_job(&fun1);
add_job(&fun2, 1);
add_job([]{}); // passing lambdas are also possible
}
See a demo in
|
74,313,612
| 74,313,663
|
declared ‘[[noreturn]]’ but its first declaration was not
|
I recently learned about the [[noreturn]] attribute and wanted to try and implement it on one of my existing code snippets.
I added the attribute to a void return type function with no return; keyword on it whatsoever. However, I'm getting this error:
[ 17%] Building CXX object CMakeFiles/Renderer.dir/src/opengl/text_render.cpp.o
/home/turgut/Desktop/CppProjects/videoo-render/src/opengl/text_render.cpp:7:25: error: function ‘const void OpenGL::Text::set_background(int, int, float, int, int, int, int, float, std::string*)’ declared ‘[[noreturn]]’ but its first declaration was not
7 | [[noreturn]] const void Text::set_background(
|
make[2]: *** [CMakeFiles/Renderer.dir/build.make:132: CMakeFiles/Renderer.dir/src/opengl/text_render.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:277: CMakeFiles/Renderer.dir/all] Error 2
make: *** [Makefile:136: all] Error 2
I'm using c++ 20+ so I don't think there is a problem with versions.
What is wrong with my usage of [[noreturn]] and how should I use it propperly? Am I missing a piece of knowledge about it?
Here is the function in question:
[[noreturn]] void Text::set_background(
int x, int y, float z,
int w, int h,
int gw, int gh,
float ang, std::string* hex_color
){
background = new Background(x-w, y-h);
background->color = (*hex_color).c_str();
background->bg_texture = new Texture(
x - 10, (1000 - y) + 10, w, -h ,gw, gh
);
background->bg_texture->init(ang, z, nullptr);
}
I've also tried to use it on some other similar functions but got a similar result.
|
The attributes needs to be in the actual declaration of the function, the one you have in the header file inside the Text class.
For the definition (implementation) of the function you don't need to use the attribute again.
On a couple of different notes, using the const qualifier for a void return type makes no sense.
And the [[noreturn]] attribute is to tell the compiler that the function doesn't return at all. For example the std::exit function doesn't return and is thus marked with that attribute.
You function do return (I assume?) so the attribute makes no sense for that function.
|
74,313,768
| 74,323,162
|
How to add shared or static library using PyTorch C++ extension?
|
How do I use torch.utils.cpp_extension.load to link shared or static library from external source?
I wrote some function in C++, and am using it in PyTorch. So I am using load function from torch.utils.cpp_extension to load a PyTorch C++ extension just-in-time (JIT).
This is the wrapper.py file's content:
import os
from torch.utils.cpp_extension import load
dir_path = os.path.dirname(os.path.realpath(__file__))
my_func = load(name='my_func', sources=[os.path.join(dir_path, 'my_func.cpp')], extra_cflags=['-fopenmp', '-O2'], extra_ldflags=['-lgomp','-lrt'])
my_func.cpp uses OpenMP, so I use the above flags.
Now, I am trying to additionally use several functions in zstd library in my_func.cpp. After cloning and makeing zstd repository, shared libraries like libzstd.so, libzstd.so.1, libzstd.so.1.5.3, and static library like libzstd.a have been created.
I've included #include <zstd.h> inside my_func.cpp and used zstd's functions.
I now have to modify wrapper.py to tell the compiler that I am using functions from zstd library.
How can I successfully compile my_func.cpp using PyTorch C++ extension's torch.utils.cpp_extension.load -- which arguments should I modify? Or, is it even possible to add external shared or static library using this method?
Frankly, I'm not familiar with the difference between static and shared library. But it seems that I can compile my_func.cpp with either one of them, i.e., g++ -fopenmp -O2 -lgomp -lrt -o my_func my_func.cpp lib/libzstd.so.1.5.3 and g++ -fopenmp -O2 -lgomp -lrt -o my_func my_func.cpp lib/libzstd.a both works.
I just can't figure out how I can do the exact same compiling using torch.utils.cpp_extension.load.
Sorry for delivering kind of a lengthy question. I just wanted to make things clear.
|
I've figured this out. extra_ldflags argument in torch.utils.cpp_extension.load can handle this. In my case, I've added libzstd.so file in my repository and added -lzstd in above argument.
|
74,314,363
| 74,315,347
|
How to delete memory for object created by *new
|
I have question regarding memory management in c++
In below example is there any memory leakage. If so how to clear memory.
Also defining int by * new is the only option to use and not int num = 25;
int main()
{
for(int i = 0;i < 200;i++)
{
int num = * new int(25);
}
I tried many ways but delete and free does not work
|
OP: Also defining int by * new is the only option to use and not int num = 25;
No, in C++ you have different ways of create new data. In short, you can create new data automatically, dynamically or statically.
automatic storage duration
A a obj;
Here you're creating an object with automatic storage duration, this means, the object will be cleaned up when it goes out of scope. This object is created directly in the current active stack frame, so is directly accesible via identifier.
dynamic storage duration
Dynamic storaged objects are created with the new operator. This objects are stored on the heap, which is an unordered (mostly) region of memory reserved to handle heap allocations. The heap isn't able to talk with the stack regions directly, but we can communicate the stack and the heap program's data with pointers.
The new operator called in front on an object constructor, will perform a heap allocation, placing the value in some place of the heap and returning a pointer to the memory address where the value resides, available in the active stack.
A* a obj = new A();
Here, we are adquiring a resource that, as C++ developers, we must take care. So, when we end with our a object, we must tell the compiler that we finished with it and that piece of memory should be released or freed. We acomplish this in C++ with the delete keyword.
A* a obj = new A();
/* snip */
delete a;
If we don't delete the dynamically constructed resource, we will produce a memory leak. This is, we lose the access (the returned pointer) to the resource, and we can't no longer reach it. So, that resource w'd be using memory until the OS claim by itself that memory (and that's could also not happen), being in a undefined behaviour state, potentially leading to crashes and other things.
static storage duration
The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration, plus those declared with static or extern
thread storage duration
The storage for the object is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the object. Only objects declared thread_local have this storage duration. thread_local can appear together with static or extern to adjust linkage.
What's wrong with your code snippet?
int num = * new int(25);
You are dynamically initializing a variable with a value. This is because you are inmediatly dereferencing the pointer that the new operator returns, losing your access to the heap allocated variable. delete won't work, because you need a pointer type to apply the operator over it, and delete the resource beyond the pointer, that will be the result of the expression new int (25). This will return an int* that will store the address of the dynamically initialized integer.
Probably, you're looking for something like:
for(int i = 0;i < 200;i++)
{
int* num = new int(25);
/* snip */
delete num;
}
TL;DR
Your deferencing, or following the pointer to the memory address that the new keyword applied on the int constructor returns to you, and then saving the value (not the pointer!) in the int num variable, losing the access to the heap allocated data, and causing a memory leak
|
74,314,609
| 74,314,707
|
Clang build an executrion file in vscode
|
I've been searching whole internet but I can't find the solution for building my c++ project with clang compiler. I'm new to all this stuff and sorry for misunderstanding.
I have default tasks.json file:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "clang++ build active file",
"command": "C:/Program Files/LLVM/bin/clang++",
"args": [
"-std=c++17",
"-stdlib=libc++",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
I can compile and this is what I've got compiled, 3 files:
I need to create executable somehow...
Thanks for help.
|
If you read the documentation (which is for MinGW but it's exactly the same for Clang for Windows), you need to explicitly add the .exe suffix to your output file.
So your "executable" file is the one named main, without any suffix or "extension".
You need to change your tasks.json file to add the .exe suffix:
"${fileDirname}/${fileBasenameNoExtension}.exe"
# Note the suffix here -------------------^^^^
|
74,315,382
| 74,315,527
|
does C++ have spread operator?
|
can you do this in C++:
vector<int> v1={1,2}, v2={3,4};
vector<int> v3={...v1, ...v2, 5};
//v3 = {1,2,3,4,5}
What is the simplest way to do this with C++ ?
|
No spread operator in C++.
Probably the simplest way would be a sequence of inserts
std::vector<int> v3;
v3.insert(v3.end(), v1.begin(), v1.end());
v3.insert(v3.end(), v2.begin(), v2.end());
v3.insert(v3.end(), 5);
Various range libraries have a concat function
auto v3 = ranges::views::concat(v1, v2, { 5 }) |
ranges::views::join |
ranges::views::to<vector>;
C++23 or ranges::v3. Still more verbose than spread operator.
|
74,315,771
| 74,316,003
|
How to delete strings from a file containing multiple lines in C++?
|
I tried this code but it deletes data if a file has only one line. When file contains multiple lines this code throws an exception. How to fix it?
int main()
{
string deleteline;
string line;
ifstream fin;
fin.open("Test1.txt");
ofstream temp1;
temp1.open("temp.txt");
deleteline="|start|";
while (getline(fin,line))
{
line.replace(line.find(deleteline), deleteline.length(), "");
temp1 << line << endl;
}
temp1.close();
fin.close();
remove("Test-1.txt");
rename("temp.txt", "Test-1.txt");
}
|
Could you please try this one ?
#include <iostream>
#include <fstream>
#include <string>
int main ()
{
std::ifstream in_file("input.txt");
std::ofstream out_file("output.txt");
std::string str;
const std::string removed_str = "|start|";
while (std::getline(in_file, str)) {
std::size_t ind = str.find(removed_str);
std::cout << str << std::endl;
if(ind != std::string::npos)
{
str.erase(ind, removed_str.length());
}
std::cout << str << std::endl;
out_file << str << std::endl;
}
return 0;
}
input.txt
Line1 |start|
Line2 |start|
Line3 Line1 Line2 |start|
output.txt
Line1
Line2
Line3 Line1 Line2
|
74,316,130
| 74,316,159
|
C++ function that deletes dynamic linked list
|
I'm currently working on a class project where we make a linked list and we're supposed to create a function that clears the list then deletes it (with "delete LIST_NAME;"). I have implemented the function as instructed by my professor, also forcing the list to become null after the delete. The function works within itself, but when it returns to the main function, the list gets a new value.
Is this sort of function just not possible in C++?
#include <iostream>
struct Node
{
int val;
Node* next;
};
struct LinkedList
{
int count;
Node* head;
Node* tail;
};
void Clear(LinkedList* list) {
Node* node = list->head;
Node* next = nullptr;
while (node != nullptr) {
next = node->next;
delete node;
node = next;
}
list->head = nullptr;
list->tail = nullptr;
list->count = 0;
}
void Destroy (LinkedList* list) {
Clear(list);
delete list;
list = nullptr;
std::cout << "\n(should be) Destroyed";
}
int main() {
//creating a list element
Node* node = new Node;
node->val = 'a';
node->next = nullptr;
//inserting the element onto list
LinkedList* list = new LinkedList;
list->count = 0;
list->head = node;
list->tail = node;
std::cout << "\nList: " << list;
Destroy(list);
std::cout << "\nList: " << list;
std::cout << "\nEND";
}
This is just a snip of my code but it shows what I mean. Using the debugger the list has the value 0x0 by the end of the function but in the main function it's assigned a new value as shown by the debugger.
|
You take list by value so it's local to the function.
If you'd like to make changes to it that are visible at the call site, take it by reference:
// `list` is now a reference to the pointer at the call site:
void Destroy(LinkedList*& list) {
Clear(list);
delete list;
list = nullptr; // this now sets the referenced `LinkedList*` to `nullptr`
std::cout << "\n(should be) Destroyed";
}
|
74,316,550
| 74,323,390
|
C++: Is there any bijective mapping between types and any other data type defined by the standard?
|
I am working on a project that makes heavy use of static polymorphism. A particular use-case that I am interested in would be made possible by static reflection, but we still don't have this in C++. The use case looks something like this: I have a functions that read/write a data structure to/from a binary file:
template <typename data_t> void write_binary(const my_type_t<data_t>& obj)
{
//write a binary file...
}
template <typename data_t> void read_binary(my_type_t<data_t>& obj)
{
//read a binary file...
}
I would like to enforce that I can only read data from files that were output by the same type, e.g. my_type_t<std::string> can only read from binary files output by my_type_t<std::string>, etc. The way I want to do this is to add a small header to the binary file that identifies the specialization of data_t:
template <typename data_t> void write_binary(const my_type_t<data_t>& obj)
{
//write header type_name(data_t)
//write a binary file...
}
template <typename data_t> void read_binary(my_type_t<data_t>& obj)
{
//read header
//assert header == type_name(data_t)
//read a binary file...
}
I am aware of the existence of typeid(data_t).name() and the various methods of demangling it, but I want something that is defined by the standard.
So my precise question is this: for any two types type1_t and type2_t, is there any C++ standard-defined mapping "F" whatsoever such that F(type1_t) == F(type2_t) always implies type1_t == type2_t, and type1_t == type2_t always implies F(type1_t) == F(type2_t), independent of compiler? That is, is there any bijective mapping between types and some kind of serializable value defined by the c++ standard?
EDIT
There is a subtlety in this question that I did not initially emphasize: I do not want to serialize arbitrary types. The function body that writes my objects to files is already implemented. What I want (as stated in the question above) is simply a unique identifier for every type that is compiler independent. The role of the template specialization data_t of my_type_t<data_t> is not to affect what information is written/read, but rather how it is interpreted.
Just a couple of other thematic points:
Due to the nature of my project, I cannot know ahead of type what type data_t will be, I must allow it to feasibly be anything.
It is very much undesirable for me to have to place requirements on what types can be used for the template specification, i.e. requiring people to implement some kind of "name" field for their types. This is because the final type data_t that ends up being used for the I/O is not tied to the interfaces that my users are exposed to.
While the details of how instances of types are stored in memory are indeed platform- and compiler-dependent, the names of the types themselves are ultimately properties only of the source code, not the compiler.
|
No.
Nor does the problem seem to benefit from one. Serialization is not generically possible in C++, so you will have customization points whether you implement them or your user does to serialize and deserialize and they will be type-specific. In other words, in:
template <typename data_t> void write_binary(const my_type_t<data_t>& obj)
{
//write header type_name(data_t)
//write a binary file...
}
The write a binary file has to be specific to data_t. There have to be cases to write a std::string differently than an int. Each of those cases can prepend an identifying header if they want. The deserialization can check that header. The deserialization can also check other invariants of the type.
requiring people to implement some kind of "name" field for their types
A customization point doesn't require a particular field. There are ways to allow customization of behavior non-intrusively such as template specialization (traits) and ADL (overloading).
the names of the types themselves are ultimately properties only of the source code
The types are a property of the source code. The names, and the spelling, are a choice of a particular formatting of the types. type_id(x).name() is one choice of formatting, which will differ on different compilers. A demangled name is another, which will differ on different platforms. Demangled names are not necessarily unique.
(Finally, using type names to identify the serialized value is cute but likely to yield surprises. For example, one would generally expect to be able to rename a class type without affecting serialized data. One would generally expect to move it to a new namespace, even with a typedef in the old location for minimal impact, without affecting serialized data.)
|
74,316,851
| 74,316,971
|
C++ Bitshift in one line influenced by processor bit width (Bug or Feature?)
|
I encountered a strange problem, but to make it clear see the code first:
#include <stdio.h>
#include <stdint.h>
int main() {
uint8_t a = 0b1000'0000; // -> one leftmost bit
uint8_t b = 0b1000'0000;
a = (a << 1) >> 1; // -> Both shifts in one line
b = b << 1; // -> Shifts separated into two individual lines
b = b >> 1;
printf("%i != %i", a, b);
return 0;
}
(using C++ 17 on a x86 machine)
If you compile the code, b is 0 while a is 128.
On a general level, this expressions should not be tied to the processors architecture or its bit width, I would expect both to be 0 after the operation
The bitshift right operator is defined to fill up the left bits with zero, as the example with b proves.
If I look at the assembler code, I can see that for b, the value is loaded from RAM into a register, shifted left, written back into RAM, read again from RAM into a register and then shifted write. On every write back into RAM, the truncation to 8 bit integer is done, removing the leftmost 1 from the byte, as it is out of range for an 8-bit integer.
For a on the other hand, the value is loaded in a register (based on the x86 architecture, 32-bit wide), shifted left, then shifted right again, shifting the 1 just back where it was, caused by the 32-bit register.
My question is now, is this one-line optimization for a a correct behavior and should be taken in account while writing code, or is it a compiler bug to be reported to the compiler developers?
|
What you're seeing is the result of integer promotion. What this means is that (in most cases) anyplace that an expression uses a type smaller than int, that type gets promoted to int.
This is detailed in section 7.6p1 of the C++17 standard:
A prvalue of an integer type other than bool, char16_t, char32_t, or
wchar_t whose integer conversion rank (7.15) is less than the rank of
int can be converted to a prvalue of type int if int can represent all
the values of the source type; otherwise, the source prvalue can be
converted to a prvalue of type unsigned int
So in this expression:
a = (a << 1) >> 1
The value of a on the right side is promoted from the uint8_t value 0x80 to the int value 0x00000080. Shifting left by one gives you 0x00000100, then shifting right again gives you 0x00000080. That value is then truncated to the size of a uint8_t to give you 0x80 when it is assigned back to a.
In this case:
b = b << 1;
The same thing happens to start: 0x80 is promoted to 0x00000080 and the shift gives you 0x00000100. Then this value is truncated to 0x00 before being assigned to b.
So this is not a bug, but expected behavior.
|
74,316,883
| 74,317,081
|
How to delete those string from file which is followed by "|" and end with "|"?
|
This code only deletes a string which I provide it in removed_str variable but I want to delete all the string which start from "|" and ends with "|". How should i do it?
int main()
{
std::ifstream in_file("Test-1.txt");
std::ofstream out_file("output.txt");
std::string str;
const std::string removed_str = "|start|";
while (std::getline(in_file, str)) {
std::size_t ind = str.find(removed_str);
std::cout << str << std::endl;
if (ind != std::string::npos)
{
str.erase(ind, removed_str.length());
}
std::cout << str << std::endl;
out_file << str << std::endl;
}
}
|
Could you please try this one ?
#include <iostream>
#include <fstream>
#include <regex>
int main ()
{
const std::regex pattern("\\|(.*?)\\|");
std::ifstream in_file("input.txt");
std::ofstream out_file("output.txt");
std::string str;
while (std::getline(in_file, str)) {
str = std::regex_replace(str, pattern, "");
std::cout << str << std::endl;
out_file << str << std::endl;
}
return 0;
}
input.txt
Line1 |start| |start|
Line2 |start| |start|
Line3 Line1 Line2 |start|
output.txt
Line1
Line2
Line3 Line1 Line2
|
74,317,702
| 74,317,905
|
Multiple functions with the same name but their parameters are either constant or received by value or by reference
|
The title is a bit lengthy, but it's best explained by an example:
Suppose we have the following functions in C++:
void SomeFunction(int num) { //1
}
void SomeFunction(int& num) { //2
}
void SomeFunction(const int& num) { //3
}
void SomeFunction(const int num) { //4
}
All of these are called the same way:
SomeFunction(5);
or
int x = 5;
SomeFunction(x);
When I tried to compile the code, it rightfully says more than one instance of overloaded function "SomeFunction" matches the argument
My question is: Is there a way to tell the compiler which function I meant to call?
I asked my lecturer if it was possible, and she tried something along
SomeFunction< /*some text which I don't remember*/ >(x);
But it didn't work and she asked me to find out and tell her.
I also encounter this post:
How to define two functions with the same name and parameters, if one of them has a reference?
And it seems that 1 and 2 can't be written together, but what about 3 and 4? Can either one of those be called specifically?
|
1 and 4 have the same signature, so you'll need to drop one of those.
The other functions cannot be called directly, but you could add a template function that allows you to specify the desired parameter type:
template<class Arg>
void Call(void f(Arg), Arg arg)
{
f(arg);
}
// Driver Program to test above functions
int main()
{
int i;
Call<int>(SomeFunction, 1);
Call<int&>(SomeFunction, i);
Call<const int&>(SomeFunction, 1);
}
Alternatively you could use a function pointer to choose the signature.
int i;
static_cast<void(*)(int)>(&SomeFunction)(1);
static_cast<void(*)(int&)>(&SomeFunction)(i);
static_cast<void(*)(const int&)>(&SomeFunction)(1);
It would be preferrable to avoid this scenario though and only define overloads for either references or the signature void SomeFunction(int).
Note:
SomeFunction<some text which I don't remember>(x);
only works for template functions and SomeFunction is not a template function, so this is not an option here.
|
74,317,971
| 74,435,993
|
Cannot format an argument. To make type T formattable provide a frormatter <T>
|
So im creating a game engine in accordance to thecherno's tutorial and I am adding GLFW Error handling(This is c++) and I cannot figure out where and how to add a formatter for SPDLOG
Here is my Log.h:
#define PL_CORE_TRACE(...) ::Pluton::Log::GetCoreLogger()->trace(__VA_ARGS__)
#define PL_CORE_WARN(...) ::Pluton::Log::GetCoreLogger()->warn(__VA_ARGS__)
#define PL_CORE_INFO(...) ::Pluton::Log::GetCoreLogger()->info(__VA_ARGS__)
#define PL_CORE_ERROR(...) ::Pluton::Log::GetCoreLogger()->error(__VA_ARGS__)
#define PL_CORE_FATAL(...) ::Pluton::Log::GetCoreLogger()->fatal(__VA_ARGS__)
__VA_ARGS__ is all the arguments given to the logger
I binded an OnEvent Function that logs like so:
void Application::OnEvent(Event& e) {
PL_CORE_INFO("{0}", e);
}
I bound the glfwSetErrorCallback event to GLFWErrorCallback function like so:
static void GLFWErrorCallback(int error, const char* description) {
PL_CORE_ERROR("GLFW Error ({0}): {1}",error,description);
}
//this is a snippit in Application::Init() which initializes GLFW
if (!s_GLFWInitialized) {
int success = glfwInit();
PL_CORE_ASSERT("GLFW NOT INITIALIZED");
glfwSetErrorCallback(GLFWErrorCallback);
s_GLFWInitialized = true;
}
I keep getting the error:
Cannot format an argument. To make type T formattable provide a formatter<T> specialization.
It is the only error and does not specify which one is causing this error as well as which type that cannot be formatted.
EDIT:
I Created this in which I wanted to return that as the format for the type of Event and I put it into my Log.cpp file which is imported in every file that uses event. The same error occurs
struct fmt::formatter<Pluton::Event> {
constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.end();
}
template <typename FormatContext>
auto format(const Pluton::Event& input, FormatContext& ctx) -> decltype(ctx.out()) {
return format_to(ctx.out(),
"(Name:{})",
input.GetName() {});
}
};
|
Add #include <spdlog/fmt/ostr.h> to Log.h file. With this spdlog would be able to use operator<< in Event.h
|
74,318,075
| 74,318,245
|
Can we have a map like this in c++ >> map <vector<int>,vector<int>> m;
|
Just a tought came in mind till now i have make maps of strings and vectors
Like this
map<int,int> m; map <int,vector<int>> m; map <string,vector<int>> m;
and various combinations are possible with other data types also.
But what will happen If I do
map <vector<int>,vector<int>> m; or map <vector<int>,vector<vector<int>>> m;
etc.
I was solving a question leetcode in which this format could be helpfull
https://leetcode.com/contest/biweekly-contest-90/problems/odd-string-difference/
I tried like this
class Solution {
public:
string oddString(vector<string>& words) {
map <vector<int>,vector<string>> m;
for(auto i:words)
{
// m[{int(i[0]-i[1]), int(i[1]-i[2])}].push_back(i);
vector<int> v;
for(int j=1;j<i.size();j++)
{
v.push_back(int(i[j]-i[j-1]));
}
}
for(auto i:m)
{
if(i.second.size() ==1)
{
return i.second[0];
}
}
return "";
}
};
|
It's perfectly fine to use std::vector<int> as a key in std::map but you'll need take a look at the requirements for a given type to be used as a key in std::map.
From the documentation:
std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.
Emphasis mine
So the Key type must meet the Compare requirements.
By default, std::map uses std::less<Key>. std::less<std::vector<int>> or in other words std::vector::operator<() lexicographically compares the values in the vector.
If you want something else, you will have to provide your own compare function when instantiating the map:
std::map<std::vector<int>, my_value_type, my_compare_function> my_map; // Note the third parameter is the compare function.
Note: That being said, when we start to use containers as key type for a map, it often is a flag indicating a wrongly designed algorithm/software architecture.
Regarding the value type in a std::map, you can have anything you want.
|
74,318,341
| 74,318,507
|
CoderPad C++ Hashmap did not work during job interview. Can you explain to me why?
|
So I had a job interview two days ago and they used coderPad.io for it, which is pretty common for job interviews. As a matter of fact, I have another job interview coming up that uses coderPad as well, so I really need to ask this question.
Essentially what happened was that my algorithm was written correctly. My interviewer told me so. However, the hash map was not working and we started debugging until the interviewer got tired and ended the interview right there. I then received a rejection email a day later. The interviewer did however narrow it down to the insert function on the hash map. We tried different ways of inserting and it still did now work.
I had to write an algorithm that needed for me to find the frequency for every integer element in a vector. However, when I had print the contents of the hash map, the frequency is always 1 for each element when it is not supposed to be 1 for each element. This had cost me the interview process to continue. I have recreated the algorithm on coderPad just now and the same issue is occurring. Here is the code:
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// To execute C++, please define "int main()"
class hashMapTester {
public:
hashMapTester() {
}
unordered_map<int, int> collectMap(vector<int>& arr) {
unordered_map<int, int> map;
for (long unsigned int i = 0; i < arr.size(); i++) {
if (map.find(arr[i]) != map.end()) {
auto freq = map.find(arr[i])->second;
freq++;
map.insert(pair<int, int> (arr[i], freq));
} else {
map.insert(pair<int, int>(arr[i], 1));
}
}
return map;
}
void printMap(unordered_map<int, int> map, vector<int>& arr) {
for (const auto& iter : map) {
cout << iter.second << endl;
}
}
};
int main() {
vector<int> arr = {1, 2, 2, 3 , 4 , 4, 4};
hashMapTester hM;
unordered_map<int, int> map = hM.collectMap(arr);
hM.printMap(map, arr);
return 0;
}
Why is the frequency portion of the map always outputting 1 when it is not supposed to ? I am stuck on this and I really need to understand why. When I use this algorithm on LeetCode or on another compiler, it works, but not on CoderPad. Can anyone please help me out ? What do I need to do to make it work on CoderPad ?
|
Per https://en.cppreference.com/w/cpp/container/unordered_map/insert, the insert method "inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key."
The call to insert in the following section won't actually change the contents of the unordered_map.
if (map.find(arr[i]) != map.end()) {
auto freq = map.find(arr[i])->second;
freq++;
map.insert(pair<int, int> (arr[i], freq)); // <<-- here
}
Option 1: Make freq a reference
if (map.find(arr[i]) != map.end()) {
auto& freq = map.find(arr[i])->second;
freq++;
}
Option 2: Simplify the algorithm,
unordered_map<int, int> collectMap(const vector<int>& arr) {
unordered_map<int, int> map;
for (int val : arr) {
++map[val];
}
return map;
}
|
74,318,422
| 74,318,436
|
does this C++ function produce a memory leak
|
If, in a function, I have the following code:
someClass *x = new object();
x = nullptr;
is this a memory leak? Or, is the memory reallocated due to its local scope?
Thanks!
Not sure how to test this on my own.
|
This is a memory leak. It is about the clearest example as one can get.
|
74,319,138
| 74,319,467
|
how do i make a console menu (c++) that i can return to after selecting something?
|
i made a simple menu and i know how to make choices and stuff but once i select a choice i don't know how to make it so that it returns to the selection menu.
#include <cmath>
#include <iostream>
#include <string>
int main()
{
std::cout << "+====| LEO'S CALCULATOR |=========+\n\n";
std::cout << "1 - Addition\n";
std::cout << "2 - Subtraction\n";
std::cout << "3 - Division\n";
std::cout << "4 - circle area\n\n";
std::cout << "+=================================+\n";
int choice;
std::cin >> choice;
// CIRCLE RADIUS
if (choice == 4)
{
std::cout << "what is the radius of your circle\n";
double radius;
double circleArea;
const double pi = 3.14;
std::cin >> radius;
circleArea = pi * pow(radius, 2);
std::cout << "the radius of your circle is: " << circleArea;
}
}
I tried to look up what I was trying to do and i saw something regarding functions and being able to call them but i couldn't understand it. I tried to make the menu a function and in the choice i attempted to call said function but obviously it didn't work
im a beginner so if you have any other suggestions on what i should change id appreciate it and suggested resources for c++ are welcome
|
With a loop (do while for example) and an option to exit the loop.
#include <iostream>
int main()
{
int choice;
do
{
std::cout << "+====| LEO'S CALCULATOR |=========+\n\n";
std::cout << "1 - Your menu...\n";
std::cout << "5 - Quit\n\n";
std::cout << "+=================================+\n";
std::cin >> choice;
// Your code.
}
while(choice != 5);
}
|
74,319,413
| 74,319,657
|
How to make a copy constructor for different types within a template class?
|
I need to make my Iterator< isConst = false> convert to Iterator<isConst = true>. That is, I need a separate method Iterator< true >(const Iterator< false > &).
My Iterator class:
template < typename T >
template < bool isConst >
class ForwardList< T >::Iterator
{
using value_type = std::conditional_t< isConst, const T, T >;
using difference_type = ptrdiff_t;
using pointer = std::conditional_t< isConst, const T *, T * >;
using reference = std::conditional_t< isConst, const T &, T & >;
using iterator_category = std::forward_iterator_tag;
friend class ForwardList< T >;
private:
explicit Iterator(node_t *nodePtr): nodePtr_(nodePtr) {}
public:
Iterator() = default;
Iterator(const Iterator &other) = default;
~Iterator() = default;
reference operator*() const;
pointer operator->() const;
Iterator &operator++();
Iterator operator++(int) &;
bool operator==(const Iterator &other) const;
bool operator!=(const Iterator &other) const;
private:
node_t *nodePtr_;
};
I tried overloading the copy constructor and specializing the template. I understand that if you split the Iterator into two classes, it can be done, but I don't want to duplicate so much code.
|
Rather than having a constructor that takes an Iterator<false>, you can have a conversion operator that returns an Iterator<true>.
operator Iterator<true>() const { return Iterator<true>(nodePtr_); }
You will need to friend class Iterator<false>; to access your private constructor.
See it live
|
74,319,497
| 74,319,557
|
c++ left shift operator used inside array declaration
|
I found this array declaration in open source software. It reads data from csv files, compares the tuples, and outputs the best tuples.
static const uint32_t SHIFTS[] = { 1 << 0, 1 << 1, 1 << 2, 1 << 3, 1 << 4,
1 << 5, 1 << 6, 1 << 7, 1 << 8, 1 << 9, 1 << 10, 1 << 11, 1 << 12, 1 << 13,
1 << 14, 1 << 15, 1 << 16, 1 << 17, 1 << 18, 1 << 19, 1 << 20, 1 << 21,
1 << 22, 1 << 23, 1 << 24, 1 << 25, 1 << 26, 1 << 27, 1 << 28, 1 << 29, 1 << 30 };
I guess this SHIFTS[] array is used in data partitioning.
Why was the left shift operator used inside the array declaration?
left shift operator <<:
left shifting an integer “x” with an integer “y” denoted as ‘(x<<y)’ is equivalent to multiplying x with 2^y (2 raised to power y).
right shifting an integer “x” with an integer “y” denoted as ‘(x>>y)‘ is equivalent to dividing x with 2^y.
Since the final value of the array would be like the following, why just not declare it as this?
static const uint32_t SHIFTS[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216,
33554432, 67108864, 134217728, 268435456, 536870912, 1073741824};
I tried to compute each shift operation on each element and found the final array value, but I could not figure out why someone would want to declare an array with the left shift operator.
|
The compiler will almost certainly generate the same static data for the two definitions. The difference is readability to human users.
The declaration using the shifts actually presents a human-readable intent, that the array ought to be full of consecutive powers of two.
In fact, it's sufficiently readable that many readers can verify that the shifts are correct and follow the intended pattern, with only a quick skim.
This makes the code less error-prone, easier to extend in the future (suppose you had to handle shifts up to 2^63 in a later version?), and otherwise easier to read.
On the other hand, readers are not expected to remember that 1073741824 == 2^30, or many other powers of two for that matter. If I had to work with the second sample of code, I'd have to spend quite a bit of effort keeping track of all of the values, calculating them with a calculator, etc.
|
74,319,524
| 74,319,711
|
What does "when the member is then reinitialized re initialized otherwise in the constructor" mean in cplusplus.com tutorial?
|
I'm reading classes tutorial in cplusplus.com.
I got confused by the following paragraph.
Default-constructing all members of a class may or may always not be convenient: in some cases, this is a waste (when the member is then reinitialized otherwise in the constructor), but in some other cases, default-construction is not even possible (when the class does not have a default constructor). In these cases, members shall be initialized in the member initialization list.
So, my question is what does the "when the member is then reinitialized otherwise in the constructor" mean? Why is a waste?
In the beginning, I think the "reinitialized` like following code.
class Son
{
int age;
public:
// default constructor
Son()
{
age = 1;
}
Son(int age) : age(age) {}
};
class Father
{
Son son; // First, I think that it will call default constructor of class Son when the object of Father was created
int age;
public:
// Then object of Father will call this constructor, then initialize son again.
Father(int sonAge, int fatherAge) : son(sonAge), age(fatherAge)
{
}
};
Then, I found Son son wasn't to define son at all, it just waited the constructor of Father to initialized son. So this isn't waste, my idea is wrong!!! Maybe I lack the knowledge of object creation order? cplusplus.com provides tutorial seems incomplete for me...
Can you give me a few code examples?
|
All objects are initialized before the body of the constructor is entered, so let's walk this through step-by-step:
int age;
Son() // age initialized here (does nothing)
{
age = 1;// age assigned new value here
}
But what if age is something more complicated than an int? What if it is a class with very expensive construction?
Expensive age;
Son() // age initialized here takes a lot of time and resources
{
age = 1;// age assigned new value here. This requires construction of a
// temporary Expensive (which takes a lot of time and resources)
// and then assigns the temporary to age (which may also be time and
// resource-consuming), wasting the effort spent on the default
// construction. The temporary is then destroyed, and that wastes
// even more
}
If you use the Member Initializer List
Expensive age;
Son(): age(1) // age initialized here takes a lot of time and resources
{
// does nothing
}
Note: The above is a worst-case example. Expensive could have an Expensive &operator=(int) that shaves off some of the work, but you still need to deal with default construction and the assignment logic in place of a single constructor call. Plus someone had to write the = overload, and code that doesn't exist has no bugs.
|
74,320,014
| 74,321,085
|
How to convert c++ string with russian (cyrillic) letters to jstring
|
I am trying to convert a c++ string with russian letters to jni jstring
But in the output of the java program i getting a different string
How i converting:
const char* msg = "привет";
return env->NewStringUTF(msg);
This returns in java:
ïðèâåò
How to do it right?
|
First, you have to make sure your input char* string is encoded in UTF-8 to begin with (which it isn't, in your example).
Second, JNI's NewStringUTF() method requires the input string to be encoded in modified UTF-8, not in standard UTF-8.
When dealing with non-ASCII chracters, you are better off using a UTF-16 encoded char16_t*/wchar_t* string with JNI's NewString() method instead.
|
74,320,233
| 74,323,478
|
Deleted function template in requires-expression, differing compiler behavior
|
Consider a function template f<T> with the primary template deleted but some specializations defined. We can use a requires-expression to test if f<T> has been specialized:
template <typename T>
int f() = delete;
template <>
int f<int>() {
return 1;
}
template <typename T>
int g() {
if constexpr (requires { f<T>; }) {
return f<T>();
} else {
return -1;
}
}
int main() { return g<void>(); }
Version 1 (godbolt link), same as above: compiles on clang but not gcc or msvc.
Version 2 (godbolt link): replacing requires { f<T>; } with requires { f<T>(); } it now compiles on gcc as well.
Version 3 (godbolt link): replacing the inline requires-expression with a named concept, it now compiles on all three compilers.
I am curious which of these versions are well-formed C++20 code and which instances represent compiler bugs.
|
Well, MSVC is definitely wrong. It thinks the requires-expression is actually true. But [dcl.fct.def.delete]/2 says:
A program that refers to a deleted function implicitly or explicitly, other than to declare, it, is ill-formed.
[Note 1: This includes calling the function implicitly or explicitly and forming a pointer or pointer-to-member to the function.
It applies even for references in expressions that are not potentially-evaluated.
For an overload set, only the function selected by overload resolution is referenced.
The implicit odr-use ([basic.def.odr]) of a virtual function does not, by itself, constitute a reference.
— end note]
The expression f<T> is an lvalue that refers to the deleted function, so it "refers" to it; this is ill-formed and it should be detected by the requires-expression.
The only question is whether the ill-formedness is actually in the immediate context. The standard doesn't explain what "immediate context" means, but going off the commonly understood meaning, the issue is whether the ill-formedness is the instantiation of the deleted f<void> (which would not be in the immediate context) or the reference to that deleted function (which would be in the immediate context). I'm inclined to go with Clang here: the instantiation itself is not ill-formed, because its effect is to instantiate f<void>, i.e., synthesize the definition of that specialization (and a definition is a declaration), rather than refer to it.
|
74,320,718
| 74,320,932
|
Why I am getting an error that no member show is declared in the class, whereas it is declared in the class
|
class "bankdeposit" has no member "show"
Here is the code:
#include <iostream>
using namespace std;
class bankdeposit
{
int principal, years;
float interest, returnvalue;
public:
bankdeposit(){};
bankdeposit(int p, int y, float r); // can be 2.00
bankdeposit(int p, int y, int r); // can be 2.
};
bankdeposit::bankdeposit(int p, int y, float r)
{
principal = p;
years = y;
interest = r;
returnvalue = principal;
for (int i = 0; i < y; i++)
{
returnvalue = returnvalue * (1 + r);
}
};
bankdeposit::bankdeposit(int p, int y, int r)
{
principal = p;
years = y;
interest = float(r) / 100;
returnvalue = principal;
for (int i = 0; i < y; i++)
{
returnvalue = returnvalue * (1 + r);
}
void show();
};
void bankdeposit::show(){
}
int main()
{
return 0;
}
|
Inside the bankdeposit(int, int, int) constructor, the expression void show(); is in the wrong place. It needs to be inside the bankdeposit class declaration instead:
class bankdeposit
{
...
public:
...
void show(); // <-- move to here
};
bankdeposit::bankdeposit(int p, int y, int r)
{
...
// void show(); // <-- remove from here
};
On a site note, your default bankdeposit() constructor is not initializing any of the class data members, so their values will be indeterminate. Either remove that constructor, or give the data members default values.
|
74,321,038
| 74,329,203
|
Trying to save unusual data type to file in binary and then write it to the vector
|
I wanted to create simple todo like program in console where you can input your task ((name) (level) (interesting level)) and it will save it from the vector to the binary file. I have this program, but when I try to save tasks to the file and then read from it, it gives me an error Segmentation fault (core dumped) and I have no ideas why... I tried to debug, bug I steel have no ideas why this is not working. Here is the git-hub link (here). What do I do?
|
As mentioned on the comments you cannot do what you are trying to do with a dynamic object such as a std::string. You will never know how big such an object is when you are loading it. Because of that, your program may start loading part of another object on to the std::string.
Your simplest solution in my opinion is to change the std::string for a fix sized array of char and limit the name size a task can have. Bellow is a fully working example.
#include <fstream>
#include <iostream>
#include <vector>
struct data
{
int m_value = 0;
int m_priority = 0;
char m_task[28] = {"\0"};
};
int main()
{
std::vector<data> dat;
data datt;
for (int i = 0; i < 4; i++)
{
sprintf( datt.m_task, "task %d", i);
datt.m_priority = i;
datt.m_value = i*4;
dat.push_back(datt);
}
std::ofstream ofile;
ofile.open("data.dat", std::ios::binary);
if (ofile.is_open())
{
for (const auto& d : dat)
ofile.write(reinterpret_cast<const char *>(&d), sizeof( d));
ofile.close();
}
std::ifstream ifile;
ifile.open("data.dat", std::ios::binary);
if (ifile.is_open())
{
while (!ifile.eof()){
ifile.read(reinterpret_cast<char *>(&datt), sizeof( datt));
std::cout << datt.m_value << " " << datt.m_priority << " " << datt.m_task << std::endl;
}
ifile.close();
}
}
|
74,321,198
| 74,326,600
|
NtProtectVirtualMemory return STATUS_ACCESS_VIOLATION?
|
I'm tried to invoke NtProtectVirtualMemory from my dll, that was attached to application using followed code:
typedef NTSTATUS(__stdcall* tNtProtectVirtualMemory) (HANDLE, IN OUT PVOID*, IN OUT PULONG, IN ULONG, OUT PULONG);
...
HMODULE Ntdll = GetModuleHandle("ntdll.dll");
if (!Ntdll) {
char outtxt[64];
sprintf(outtxt, "GetModuleHandle error %d", GetLastError());
MessageBox(NULL, outtxt, "error", MB_OK);
}
tNtProtectVirtualMemory OrigNtProtectVirtualMemory = (tNtProtectVirtualMemory)GetProcAddress(Ntdll, "NtProtectVirtualMemory");
if (!OrigNtProtectVirtualMemory) {
char outtxt[64];
sprintf(outtxt, "tNtProtectVirtualMemory is null (%d)", GetLastError());
MessageBox(NULL, outtxt, "error", MB_OK);
}
NTSTATUS sts = OrigNtProtectVirtualMemory(-1, sectionData->address, sectionData->size, protect, &oldProtect);
GetModuleHandle returns correct handle and GetProcAddress works fine. NtProtectVirtualMemory returns 0xC0000005 (STATUS_ACCESS_VIOLATION).
Now what's most interesting: VirtualProtect works without any errors:
VirtualProtect(sectionData->address, sectionData->size, protect, &oldProtect);
But I have to use exactly NtProtectVirtualMemory. Any ideas?
|
Unlike VirtualProtectEx, the NtProtectVirtualMemory function takes a pointer to the pointer that points to the address of the region whose protection is to be changed, and a pointer to the size:
ULONG oldProtect;
ULONG size = sectionData->size;
PVOID address = sectionData->address;
NTSTATUS sts = OrigNtProtectVirtualMemory((HANDLE)-1, &address, &size, protect, &oldProtect);
To add more information, the (HANDLE)-1 process handle means to take the current process handle - without the need to open the current process, I found this by reversing the ntdll.dll, but couldn't find any documentation about it.
|
74,321,386
| 74,321,549
|
does the value I did allocate to an adress inside the memory stay?
|
lets say I initialized a value (ex 10) to a variable A in c++ after that I ended my program and coded another program, in that program I declared a variable B and by a miracle it was allocated at the same address of the variable A that I located in my first program so, does the value of the first variable (A) will be given to the second one (B) if i didn't initialize a value to it?
I tried to use the cstdint library to get the located value of a specific address but when I tried to do that I got a segmentation fault.
my code :
#include <cstdint>
int main()
{
uintptr_t p = 0x0001FBDC;
int value = *reinterpret_cast<int *>(p);
}
|
Firstly, your process is almost certainly working with virtual memory addresses. That means the address 0x0001FBDC does not necessarily refer to the same physical memory across runs (or even during a single run).
Ignoring that, in general, your program has to share the same physical memory with all other applications (not at the same time, but obviously the system memory is reused by all processes). But your program might have left sensitive data in memory and letting other programs access that would be a security concern.
For that reason, in general, once your program is closed and some other program wants to use the same memory, the operating system zeros-out the section and only then hands it out to other programs. This also has the nice consequence that global variables are zero-initialized cheaply for you (which is a mandated standard behavior).
So, no, you can't access the same variable across runs. Some operating systems will allow you to allocate memory and share across processes, so you might want to look into that.
But, of course, none of this is guaranteed to happen. You might be running your program on an embedded system with no OS or memory protection, and then you might observe that a particular address that is not overwritten by anything else (other programs, other functions in your program, etc.) keeps its value.
|
74,322,155
| 74,323,321
|
Passing array of class objects
|
I've been trying for a long time to pass an array of objects to another class object.
In settingUp.cpp:
//** Status classes and their functions **//
void settingUp(){
dataClass prueba0;
dataClass prueba1;
dataClass prueba2;
const dataClass * arrayPrueba[3];
prueba0.setValues(1);
prueba1.setValues(2);
prueba2.setValues(3);
arrayPrueba[0] = &prueba0;
arrayPrueba[1] = &prueba1;
arrayPrueba[2] = &prueba2;
statusClass status;
status.setValues(1, arrayPrueba);
status.printValues();
}
In classData.cpp:
//** dataClass and their functions **//
void dataClass::setValues(int _length){
length = _length;
}
void dataClass::printValues() const{
printf("TP: dataClass: length = %d\n", &length);
};
In statusClass.cpp:
//** Status classes and their functions **//
void statusClass::setValues (uint8_t _statusSelectorByte, const dataClass **_array){
newStatusSelectorByte = _statusSelectorByte;
array = *_array;
};
void statusClass::printValues(){
printf("TP: statusClass -> printValues: Prueba = %d\n", newStatusSelectorByte);
printf("TP: statusClass -> printValues: arrayPrueba = %d\n", array[1].length);
}
When I call:
status.printValues();
I can read only the fist element of the arrayPrueba.
|
In statusClass::setValues(), *_array is the same as _array[0]. You are storing only the first dataClass* pointer from the input array.
Later, when using array[1], you are mistreating array as-if it were a pointer to an array of objects, when it is really a pointer to a single object instead. You are thus reaching past that object into surrounding memory, which is undefined behavior (but may "work" in this case because an object may happen to actually exist at that location, but this is bad behavior to rely on).
You need to store the original array pointer, not a single element taken from the array.
private:
const dataClass **array; // <-- add an *
void statusClass::setValues (uint8_t _statusSelectorByte, const dataClass **_array){
newStatusSelectorByte = _statusSelectorByte;
array = _array; // <-- get rid of the *
};
void statusClass::printValues(){
printf("TP: statusClass -> printValues: Prueba = %d\n", newStatusSelectorByte);
printf("TP: statusClass -> printValues: arrayPrueba = %d\n", array[1]->length); // use -> instead of .
}
On a side note: in dataClass::printValues(), you need to drop the & when printing the value of length:
printf("TP: dataClass: length = %d\n", length);
|
74,322,508
| 74,322,854
|
How to push string in a given range in stack in C++?
|
int main()
{
istringstream iss(dtr);
Stack <string> mudassir;
mudassir.push1(s1);
string subs;
do {
iss >> subs;
if (subs == "|post_exp|")
{
iss >> subs;
while (subs != "|\\post_exp|")
{
mudassir.push(subs);
cout << "heloo";
iss >> subs;
}
}
} while (iss);
}
I want to push a certain element of string in stack. But the problem is in this code, the inner while loop which has hello (just for testing) in it is running infinitely. I don't know why.
|
the inner while loop which has hello (just for testing) in it is running infinitely. I don't know why.
Your inner while loop is not taking into account when the stream reaches the end of its data.
When operator>> reaches the end of the stream, it will put the stream into the eofbit state, and subs will be set to whatever data was left in the stream. Subsequent reads with operator>> will put the stream into the failbit state, and set subs to a blank value.
Your inner loop is ignoring the stream's state completely, and the blank value satisfies the != condition that you are checking. That is why your loop runs forever.
You need to pay attention to the stream's state. For example:
int main()
{
istringstream iss(dtr);
Stack <string> mudassir;
mudassir.push1(s1);
string subs;
while (iss >> subs) {
if (subs == "|post_exp|")
{
while (iss >> subs && subs != "|\\post_exp|")
{
mudassir.push(subs);
cout << "heloo";
}
}
}
}
|
74,322,604
| 74,324,649
|
How can I load an image from the OpenGL/Glfw clipboard?
|
I am making a program that loads images and displays them with OpenGL / Glfw. I have managed to load the images from a path but I also want to do it from the windows clipboard. With text it works for me to read it. But when I copy an image from windows explorer nothing comes up or it tells me that the clipboard is empty.
bool FeatherGUI::loadFromClipBoard() {
std::cout << "Loading from clipboard" << std::endl;
//Show content of clipboard with glfwGetClipboardString
const char* clipboard = glfwGetClipboardString(this->windowContext);
if (clipboard == NULL) {
std::cout << "Clipboard is empty" << std::endl;
return false;
}else{
std::cout << "Clipboard content: " << clipboard << std::endl;
}
return true;
}
How can I get what I want?
|
GLFW doesn't provide that functionality at the moment.
See issue #260, "Support for clipboard image data".
GLFW's Windows implementation of glfwPlatformGetClipboardString() lives in src/win32_window.c if you feel like taking a stab at adding CF_BITMAP/CF_DIB/CF_DIBV5 support.
|
74,322,768
| 74,323,090
|
Is it possible to access a variable template without the template parameter?
|
I am not sure if this is viable. I want to initialize a variable template inside a constructor of my class.
template<typename T>
T var_tem;
Struct A {
template<typename U>
A(U u) { var_tem<U> = u;}
};
I am wondering if it's possible to access var_tem<U> later without knowing the type U. Also, I know whenever I access var_tem<>, only one instantiation exists. This would be much easier if I make my class hold var_tem as member data. But I have other methods I would rather not make templates due to issues discussed here section attribute of a function template is silently ignored in GCC. Basically, I have some internal static data needed to be emitted to a specific section.
|
The information of the type U is not available after the call to constructor. However, at the point of access, you also need to be aware of the type, otherwise you wouldn't know what you can do with it. So either you specify the type directly, or you're passing a visitor.
Now, for visitors, as long as there's a compile-time limited set of signatures, it's doable. All you need is to enumerate these types and have a type switch (and store the pointer to the variable):
template<typename T>
T var_tem;
Struct A {
template<typename U>
A(U u)
{
var_tem<U> = u;
var = &var_tem<U>;
}
void tryVisit() {}
template<typename V, typename T, typename... Ts>
void tryVisit(V& v)
{
if (var == &var_tem<T>) {
v(*static_cast<T*>(var));
} else {
tryVisit<V, Ts...>(v);
}
}
}
}
private:
void* var;
};
If listing the types is not an option, there's one more possibility, but it's only recommended for error handlers: you might throw it as an exception. Exception handlers are chainable, so you don't need a specific point at which you have all the possible types (but handlers are still listed on the stack). Note that you can only handle specific types this way, there are no template exception handlers. The throw function can then be stored as an std::function<void(void)>:
template<typename T>
T var_tem;
Struct A {
template<typename U>
A(U u)
: throwTheVar([]() { throw var_tem<U>; })
{ var_tem<U> = u; }
void throwAsError() { throwTheVar(); }
private:
std::function<void()> throwTheVar;
};
If it's not an error handler, then I wouldn't suggest throw; but you might still populate a limited interface of std::function<>s using this lambda logic. The problem with it is that it's very slow: internally, std::function<> is either a virtual or a function pointer, depending on your implementation.
|
74,323,099
| 74,323,310
|
How can I return unordered_map with a hash function to something expecting just `unordered_map<string, string>`
|
I want to implement an unordered_map<string, string> that ignores case in the keys. My code looks like:
std::unordered_map<std::string, std::string> noCaseMap()
{
struct hasher {
std::size_t operator()(const std::string& key) const {
return std::hash<std::string>{}(toLower(key));
}
};
std::unordered_map<std::string, std::string, hasher> ret;
return ret;
}
but XCode flags the return statement with this error:
foo.cpp:181:20 No viable conversion from returned value of type 'unordered_map<[2 * ...], hasher>' to function return type 'unordered_map<[2 * ...], (default) std::hash<std::string>>'
I tried casting ret to <std::unordered_map<std::string, std::string>>, but XCode wasn't having it.
I tried making my hasher a subclass of std::hash<std::string> but that made no difference.
Edit: this is a slight oversimplification of the problem; I know I also have to implement a case-insensitive equal_to() functor as well.
|
You can't. There's a reason it's part of the type: efficiency. What you can do is e.g. store everything lowercase. If you need both lowercase and case-preserving, you might need two maps; but, at this point, I'd consider requesting an interface change.
|
74,323,131
| 74,323,312
|
Why doesn't sort this code the German words?
|
I'm trying to sort German words with their articles, but it don't work perfectly. Can you help me?
Code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <stdio.h>
using namespace std;
struct asd
{
string ne;
string fn;
};
int main()
{
asd szavak[50];
ifstream be("nemet.txt");
int db=0;
while (!be.eof())
{
be>>szavak[db].ne;
be>>szavak[db].fn;
cout<<szavak[db].ne<< " "<<szavak[db].fn<<endl;
db++;
}
be.close();
cout<< "\n\n"<< "Rendezve:\n";
for (int i=0; i<db-1; i++)
{
for (int j=i+1; j<db; j++)
{
if (szavak[j].ne<szavak[i].ne)
{
swap(szavak[j].ne,szavak[i].ne);
swap(szavak[j].fn,szavak[i].fn);
}
}
}
int sv1=0;
int sv2=0;
int sv3=0;
for (int i=0; i<db; i++)
{
if (szavak[i].ne=="das")
{
sv1++;
}
if (szavak[i].ne=="der")
{
sv2++;
}
if (szavak[i].ne=="die")
{
sv3++;
}
}
for (int j=0; j<sv1-1; j++)
{
for (int k=j+1; k<sv1; k++)
{
if (szavak[k].fn<szavak[j].fn)
{
swap(szavak[k].fn,szavak[j].fn);
}
}
}
for (int h=sv1; h<sv1+sv2-1; h++)
{
for (int f=h+1; f<sv2; f++)
{
if (szavak[f].fn<szavak[h].fn)
{
swap(szavak[f].fn,szavak[h].fn);
}
}
}
for (int s=sv1+sv2; s<sv1+sv2+sv3-1; s++)
{
for (int l=s+1; l<sv3; l++)
{
if (szavak[l].fn<szavak[s].fn)
{
swap(szavak[l].fn,szavak[s].fn);
}
}
}
for (int i=0; i<db; i++)
{
cout<<szavak[i].ne<< " "<<szavak[i].fn<<endl;
}
return 0;
}
I expected it to sort the words correctly after 'das' too, but it didn't.
Here are the words that I used in the txt(one word in one line):
der Hafen
die Anzeige
das Einfamilienhaus
das Mehrfmilienhaus
der Mitbewohner
die Miete
die Badewanne
das Badezimmer
das Wohnzimmer
die Aussicht
das Arbeitszimmer
die Decke
der Plattenbau
der Altbau
der Neubau
der Hund
das Zimmer
das Bild
der Spiegel
die Kindern
die Waschmaschine
|
I haven't checked the validity of your code (it's a bit hard to read), but you should always resort to the algorithms supplied by the standard library (unless of course you want to learn how to write sorting algorithms). This helps to prevent bugs like this. In your case you can use the std::sort algorithm if you provide a comparison function for asd which only compares ne.
Sorting based on ne
The following example provides the comparison function in form of a lambda expression.
std::sort(
std::begin(szavak),
std::end(szavak),
[](asd const& a, asd const& b){ return a.ne < b.ne; }
);
for (auto const& a : szavak){
std::cout << a.ne << " " << a.fn << std::endl;
}
Output:
das Einfamilienhaus
das Mehrfmilienhaus
das Badezimmer
das Wohnzimmer
das Bild
das Arbeitszimmer
das Zimmer
der Hafen
der Mitbewohner
der Spiegel
der Plattenbau
der Altbau
der Neubau
der Hund
die Waschmaschine
die Kindern
die Decke
die Aussicht
die Badewanne
die Miete
die Anzeige
See here for a live code example
Sorting first by ne, then by fn
If you want to sort first by article, then by noun, you can wrap ne and fn in tuples using std::tie. tuples are by default compared lexicographically
std::sort(
std::begin(szavak),
std::end(szavak),
[](asd const& a, asd const& b){
return std::tie(a.ne, a.fn) < std::tie(b.ne, b.fn);
}
);
Output:
das Arbeitszimmer
das Badezimmer
das Bild
das Einfamilienhaus
das Mehrfmilienhaus
das Wohnzimmer
das Zimmer
der Altbau
der Hafen
der Hund
der Mitbewohner
der Neubau
der Plattenbau
der Spiegel
die Anzeige
die Aussicht
die Badewanne
die Decke
die Kindern
die Miete
die Waschmaschine
See here for a live code example
Bubble sort
If you do want to learn how to write a sorting algorithm, I would start by assuming that you have a comparison function for the elements in your array that returns true, if two elements are in order and false otherwise. Then you write your sorting algorithm with the use of this comparison function.
This makes your sorting algorithm more general, as you could pass in any comparison function you like. In addition, you can concentrate on the algorithm itself without having to worry about the types of objects that you are sorting or the criterium by which you are sorting them.
A simple bubble sort implementation based on forward iterators and a callable Comparator object could look like this:
template <typename ForwardIt, typename Comparator>
void sort(ForwardIt begin, ForwardIt end, Comparator const& comp)
{
bool is_sorted = false;
while (!is_sorted){
is_sorted = true; // assume the container is sorted for now
ForwardIt current = begin;
ForwardIt next = current;
++next;
while(next != end){
if (!comp(*current, *next)) {
/* swap them and remember something changed */
std::iter_swap(current, next);
is_sorted = false;
}
++current;
++next;
}
}
}
Note that the implementation makes no assumption on the type of objects in the array and no assumption on the criterium by which they shall be sorted. You only use
an iterator current pointing to an element in the list that can be incremented to obtain the next element in the list
std::iter_swap to swap the values that two iterators point to.
A templated Comparator function, which must be invokable on two const references to objects in the list and return a bool.
See here for a live code example
|
74,323,238
| 74,323,301
|
How to use preprocessor IF on DEFINE that is an ENUM member?
|
I am struggling with this for a while now, and cant get it to work!
I have a preprocessor define for LOG_LEVEL which defines what logs my program should emit.
I Have a lot of LOG points, so performance is needed,
therefore, no use of runtime check for log_level.
I trimmed my code to the minimal problematic construct which can be played with (here)[https://onlinegdb.com/u39ueqNAI]:
#include <iostream>
typedef enum {
LOG_SILENT=0,
LOG_ERROR,
LOG_WARNING,
LOG_INFO,
LOG_DEBUG
} E_LOG_LEVELS;
// this define is set using -DLOG_LEVEL=LOG_WARNING to the compiler.
#define LOG_LEVEL LOG_WARNING
int main() {
std::cout << "Logging Level Value is " << LOG_LEVEL << std::endl; // output 2 (correctly)
#if LOG_LEVEL==LOG_WARNING
std::cout << "Log Level Warning!" << std::endl; // outputs (correctly)
#endif
#if LOG_LEVEL==LOG_ERROR
std::cout << "Log Level Error!" << std::endl; // outputs (Why ??? )
#endif
return 0;
}
The main issue is that the #if LOG_LEVEL==LOG_* always true.
I also tried #if LOG_LEVEL==2 but this returned FALSE (uff).
what's going on ?
how can I test that a define is an enum value ?
|
You don't need the preprocessor for this. A normal
if (LOG_LEVEL <= LOG_WARNING)
will not create a runtime test when the condition involves only constants and the build has any optimization at all.
Modern C++ allows you to force the compiler to implement the conditional at compile-time, using if constexpr (...). This will prune away dead branches even with optimization disabled.
Finally, if you insist on using the preprocessor, and you can guarantee that the macro will use the symbolic name (you'll never build with g++ -DLOG_LEVEL=2), then you can
#define STRINGIFY(x) #x
#define STRINGY2(x) STRINGIFY(x)
#define PP_LOG_LEVEL STRINGY2(LOG_LEVEL)
#define LOG_LEVEL_IS(x) STRINGY2(LOG_LEVEL)==STRINGIFY(x)
then either
#if PP_LOG_LEVEL=="LOG_WARNING"
or
#if PP_LOG_LEVEL_IS(LOG_WARNING)
But I would recommend avoiding preprocessor string comparison for this.
If you do use the preprocessor, I recommend checking the actual value against a whitelist and using #error to stop the build in case LOG_LEVEL isn't set to any of the approved names.
|
74,323,336
| 74,323,481
|
Partial template specialization on class methods using enable_if
|
I have a templated class, for which I want to specialize one of the methods for integral types. I see a lot of examples to do this for templated functions using enable_if trait, but I just can't seem to get the right syntax for doing this on a class method.
What am I doing wrong?
#include <iostream>
using namespace std;
template<typename T>
class Base {
public:
virtual ~Base() {};
void f() {
cout << "base\n";
};
};
template<typename Q>
void Base<std::enable_if<std::is_integral<Q>::value>::type>::f() {
cout << "integral\n";
}
template<typename Q>
void Base<!std::enable_if<!std::is_integral<Q>::value>::type>::f() {
cout << "non-integral\n";
}
int main()
{
Base<int> i;
i.f();
Base<std::string> s;
s.f();
return 0;
}
the above code does not compile:
main.cpp:16:60: error: type/value mismatch at argument 1 in template parameter list for ‘template class Base’
16 | void Base<std::enable_if<!std::is_integral<Q>::value>::type>::f() {
| ^
main.cpp:16:60: note: expected a type, got ‘std::enable_if<(! std::is_integral<_Tp>::value)>::type’
main.cpp:21:61: error: type/value mismatch at argument 1 in template parameter list for ‘template class Base’
21 | void Base<!std::enable_if<!std::is_integral<Q>::value>::type>::f() {
| ^
main.cpp:21:61: note: expected a type, got ‘! std::enable_if<(! std::is_integral<_Tp>::value)>::type’
main.cpp:21:6: error: redefinition of ‘template void f()’
21 | void Base<!std::enable_if<!std::is_integral<Q>::value>::type>::f() {
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:16:6: note: ‘template void f()’ previously declared here
16 | void Base<std::enable_if<!std::is_integral<Q>::value>::type>::f() {
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
Some fixes are required to your code.
First, this isn't partial specialization. If it was specialization then you could only specialize the whole class template not just one method of it.
You placed the ! in the wrong place. std::enable_if<....>::type is a type, !std::enable_if<....>::type does not make sense. You want to enable one function when std::is_integral<T>::value and the other if !std::is_integral<T>::value.
You can write two overloads like this:
#include <iostream>
using namespace std;
template<typename T>
class Base {
public:
virtual ~Base() {};
template<typename Q = T>
std::enable_if_t<std::is_integral<Q>::value> f() {
cout << "integral\n";
}
template<typename Q = T>
std::enable_if_t<!std::is_integral<Q>::value> f() {
cout << "non-integral\n";
}
};
int main()
{
Base<int> i;
i.f();
Base<std::string> s;
s.f();
return 0;
}
The SFINAE is on the return type. Q is just to have a template argument (required for SFINAE). Either std::is_integral<T>::value is true or not and only one of the two overloads is not a substitution failure. When it is not a substitution failure then std::enable_if_t< ...> is void.
|
74,323,453
| 74,323,519
|
compiler error in Visual Studio when std::reduce is invoked for different iterator and init types
|
Please consider the follownig simple code snippet:
template<typename T>
struct point2{ T x, y; };
template<typename T>
std::complex<T> foo(std::vector<point2<T>> const& x)
{
std::reduce(std::execution::par_unseq, x.begin(), x.end(), std::complex<T>{},
[&](std::complex<T> const& first, point2<T> const& second) {
return first + std::complex<T>{ second.x, second.y };
});
}
Using Visual Studio 2022 (with C++-Language set to C++20), I'm receiving the error message
'int foo::<lambda_1>::operator ()(const std::complex &,const
point2 &) const': cannot convert argument 2 from
'std::complex' to 'const point2 &'
What is going wrong here? It seems like the type to which the iterators in the definition of std::reduce point to need to be the same as the chosen init value. But this doesn't seem to be a requirement described in the C++ standard. Am I missing something?
|
std::reduce allows elements in the set to be grouped and rearranged in any order to allow for more efficient implementations. It is required that all combinations of *first and init are valid arguments to the binary_op (quote from 27.10.4 Reduce #5):
Mandates: All of
binary_op(init, *first),
binary_op(*first, init),
binary_op(init, init), and
binary_op(*first, *first)
are convertible to T.
You seem to be looking for std::accumulate, which has the same effects, but ensures that order of evaluation is kept.
To keep possibility of using std::execution::par_unseq, you may try to add conversions between point2 and std::complex:
template<typename T>
struct point2{
T x, y;
point2(const std::complex<T>& c): x{c.real()}, y{c.imag()} {}
// Or replace first argument in lambda with point2<T>
// instead of this conversion operator, and adjust the rest accordingly
operator std::complex<T>() { return {x, y};}
};
Altough I'm not sure if the conversions won't take away the benefit of parallelizing the algorithm, you should test and profile both versions before using them.
|
74,323,723
| 74,323,838
|
Is there a technical reason why an enumerator is not a literal?
|
I thought that the enumerators of an enum [class] were literals, because, to my understanding, they represent for their enum [class] what 1 represents for int, true for bool, and "hello" for char const*. However, they are not, because the standard lists only these literals,
literal:
integer-literal
character-literal
floating-point-literal
string-literal
boolean-literal
pointer-literal
user-defined-literal
whereas the word literal doesn't occur at all in [dccl.enum].
Is there a reason why the standard doesn't classify enumerators as literals of the enumeration type they belong to?
|
Is there a technical reason why an enumerator is not a literal?
You'll notice that the term "literal" is defined in the C++ standard chapter "Lexical conventions". "Lexical" here refers to Lexical analysis, which takes a sequence of characters and generates a sequence of tokens. These tokens then undergo grammatical processing.
C++ defines various classes of tokens. Among these are keywords, operators, punctuation, identifiers, and yes literals. But that's all a literal is: a kind of token. A classification of the lexical analysis of a sequence of characters.
An enumerator is not the product of lexical analysis of characters; it's the product of syntactic analysis of a sequence of tokens. Consider this sequence of text: name1::name2. Lexically, you know what this is: it's an identifier followed by the :: operator, followed by an identifier.
Grammatically however... you have no idea. Maybe name1 designates a class and name2 is a member of that class. Maybe name1 is a namespace and name2 is a member of that namespace. Or... maybe name1 is an enumeration and name2 is an enumerator within that enumeration.
You cannot know just from the sequence of text in isolation. Syntax is a matter of context, and without context, all you have is a bunch of tokens.
An enumerator cannot be a literal because the determination of what is or is not an enumerator is a product of a process that happens after the determination of what is and is not a literal.
|
74,325,702
| 74,331,910
|
Is it possible to make a vector of ranges in cpp20
|
Let's say I have a a vector<vector<int>>. I want to use ranges::transform in such a way that I get
vector<vector<int>> original_vectors;
using T = decltype(ranges::views::transform(original_vectors[0], [&](int x){
return x;
}));
vector<int> transformation_coeff;
vector<T> transformed_vectors;
for(int i=0;i<n;i++){
transformed_vectors.push_back(ranges::views::transform(original_vectors[i], [&](int x){
return x * transformation_coeff[i];
}));
}
Is such a transformation, or something similar, currently possible in C++?
I know its possible to simply store the transformation_coeff, but it's inconvenient to apply it at every step. (This will be repeated multiple times so it needs to be done in O(log n), therefore I can't explicitly apply the transformation).
|
It is not possible in general to store different ranges in a homogeneous collection like std::vector, because different ranges usually have different types, especially if transforms using lambdas are involved. No two lambdas have the same type and the type of the lambda will be part of the range type. If the signatures of the functions you want to pass to the transform are the same, you could wrap the lambdas in std::function as suggested by @IlCapitano (https://godbolt.org/z/zGETzG4xW). Note that this comes at the cost of the additional overhead std::function entails.
A better option might be to create a range of ranges.
If I understand you correctly, you have a vector of n vectors, e.g.
std::vector<std::vector<int>> original_vector = {
{1, 5, 10},
{2, 4, 8},
{5, 10, 15}
};
and a vector of n coefficients, e.g.
std::vector<int> transformation_coeff = {2, 1, 3};
and you want a range of ranges representing the transformed vectors, where the ith range represents the ith vector's elements which have been multiplied by the ith coefficient:
{
{ 2, 10, 20}, // {1, 5, 10} * 2
{ 2, 4, 8}, // {2, 4, 8} * 1
{15, 30, 45} // {5, 10, 15} * 3
}
Did I understand you correctly? If yes, I don't understand what you mean with your complexity requirement of O(log n). What does n refer to in this scenario? How would this calculation be possible in less than n steps? Here is a solution that gives you the range of ranges you want. Evaluating this range requires O(n*m) multiplications, where m is an upper bound for the number of elements in each inner vector. I don't think it can be done in less steps because you have to multiply each element in original_vector once. Of course, you can always just evaluate part of the range, because the evaluation is lazy.
C++20
The strategy is to first create a range for the transformed i-th vector given the index i. Then you can create a range of ints using std::views::iota and transform it to the inner ranges:
auto transformed_ranges = std::views::iota(0) | std::views::transform(
[=](int i){
// get a range containing only the ith inner range
auto ith = original_vector | std::views::drop(i) | std::views::take(1) | std::views::join;
// transform the ith inner range
return ith | std::views::transform(
[=](auto const& x){
return x * transformation_coeff[i];
}
);
}
);
You can now do
for (auto const& transformed_range : transformed_ranges){
for (auto const& val : transformed_range){
std::cout << val << " ";
}
std::cout<<"\n";
}
Output:
2 10 20
2 4 8
15 30 45
Full Code on Godbolt Compiler Explorer
C++23
This is the perfect job for C++23's std::views::zip_transform:
auto transformed_ranges = std::views::zip_transform(
[=](auto const& ith, auto const& coeff){
return ith | std::views::transform(
[=](auto const& x){
return x * coeff;
}
);
},
original_vector,
transformation_coeff
);
It's a bit shorter and has the added benefit that transformation_coeff is treated as a range as well:
It is more general, because we are not restricted to std::vectors
In the C++20 solution you get undefined behaviour without additional size checking if transformation_coeff.size() < original_vector.size() because we are indexing into the vector, while the C++23 solution would just return a range with fewer elements.
Full Code on Godbold Compiler Explorer
|
74,325,837
| 74,347,183
|
Import a std::vector<Mat> to specific index of 3D cv::Mat
|
I have a vectorimageSlices and a 3D :
cv::Mat RTstruct3D(3,DImensions3D, CV_8U, Scalar(0))
I want to put my vector into the specific index of 3D cv::Mat.
//Make a 3D Organ
int programCounter = 0;
vector<Mat>imageSlices;
for (size_t k = 0; k < Npoint_Z.size(); k++)
{
Mat finalSliceImage = Mat :: zeros(DImensions3D[0], DImensions3D[1],CV_8U);
vector<vector<int>> polies;
for (size_t h = 0; h < Npoint_Z[k][0]; h++)
{
vector<int>x_y;
x_y.push_back(ContourData[programCounter][0]); //x
x_y.push_back(ContourData[programCounter][1]); //y
polies.push_back(x_y);
programCounter++;
}
fillPoly(finalSliceImage, polies, Scalar(0, 255, 0));
imageSlices.push_back(finalSliceImage);
}
//Add Organ to RTSTRUCT 3D
Mat RTstruct3D(3,DImensions3D, CV_8U, Scalar(0));
Something like this image:
Please help me! Thanks.
|
//Add Organ to RTSTRUCT 3D
vector<Mat>RTstruct3D(DImensions3D[0], Mat(DImensions3D[1], DImensions3D[2], CV_8U));
for (size_t i = 0; i < Npoint_Z.size(); i++)
{
RTstruct3D[Npoint_Z[i][1]] = imageSlices[i];
}
|
74,326,065
| 74,326,195
|
C++ coder for marks need help fixing it
|
I was trying to learn c++ i wanted to find marks using the code the issue is that it is not giving me the correct output and i wanted it to loop if the marks are less i wawnted to repeat it .
This is the code that i wrote
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
void mygrade(int grades)
{
if (grades >= 90)
{
printf("High distinction");
}
else if (grades > 80 < 70)
{
printf("Your Grade is Distinciton");
}
else if (grades > 60 < 70)
{
printf("Credit");
}
else if (grades > 50 < 60)
{
printf("Pass");
}
else if (grades < 50)
{
printf("Fail");
}
else
{
printf("Enter vaild Marks");
}
}
void main()
{
int grades;
printf("Enter your score for this unit\n");
scanf("%d", &grades);
printf("your grade for this unit is: %d ");
}
|
If you want the program work as you write in the picture, there are three things to do:
You can just use
if (grades >= 90)
// …
else if (grades >=80)
// …
// and so on
since else if statement will be trigger only if all cases above it are not true.
You need to call mygrade() function in the main() function so that it will run.
If you want to repeat the program if the grades are less than 50, then you can use do-while loop.
do
{
//…
}while (grades < 50);
|
74,326,353
| 74,326,595
|
printing the below pattern using just one loop
|
ive got the below code to print a pattern (attached below). However i'd like to just use one loop
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
cout<<"*";
}
for(int j=1;j<=n-i;j++){
if(j%2!=0){
cout<<"_";
}else{
cout<<".";
}
}
cout<<endl;
}
for(int i=1;i<n;i++){
for(int j=1;j<=n-i;j++){
cout<<"*";
}
for(int j=1;j<=i;j++){
if(j%2==0){
cout<<".";
}else{
cout<<"_";
}
}
cout<<endl;
}
}
when n = 5, heres the output.
*_._.
**_._
***_.
****_
*****
****_
***_.
**_._
*_._.
how do i just make this into one single loop
|
Try this and see how it does what you want to understand the step you did not find on your own:
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n*2-1; i++) {
if (i <= n)
{
for (int j = 1; j <= i; j++) {
cout << "*";
}
for (int j = 1; j <= n - i; j++) {
if (j % 2 != 0) {
cout << "_";
}
else {
cout << ".";
}
}
cout << endl;
}
else
{
for (int j = 1; j <= n*2 - i; j++) {
cout << "*";
}
for (int j = 1; j <= i-n; j++) {
if (j % 2 == 0) {
cout << ".";
}
else {
cout << "_";
}
}
cout << endl;
}
}
}
|
74,326,803
| 74,326,863
|
C++ Reuse out-of-class comparsion operators of base for derived class
|
Snippet
struct A {
int a;
};
bool operator==(const A& lhs, const A& rhs) { return lhs.a == rhs.a; }
template <typename T>
bool operator==(const A& lhs, const T& rhs) {
return lhs.a == rhs;
}
template <typename T>
bool operator==(const T& rhs, const A& lhs) {
return lhs.a == rhs;
}
struct B : public A {
};
int main() {
A a1, a2;
B b1, b2;
auto c1 = a1 == a2;
auto c2 = static_cast<A>(b1) == static_cast<A>(b2);
auto c3 = b1 == b2;
}
Is it possible to make the last comparison b1 == b2 work without a static_cast?
Is a reuse of the out-of-class comparison operators of A possible without redefining explicit comparison operators for B?
Example on godbolt
EDIT: I forgot to mention that A is immutable to me. I have no access to it and its comparison operators.
|
Is it possible to make the last comparison b1 == b2 work without a static_cast?
Yes, you can use SFINAE as shown below:
bool operator==(const A& lhs, const A& rhs) { return lhs.a == rhs.a; }
template <typename T>
typename std::enable_if_t<!std::is_same_v<T, B>, bool > operator==(const A& lhs, const T& rhs) {
return lhs.a == rhs;
}
template <typename T>
typename std::enable_if_t<!std::is_same_v<T, B>,bool> operator==(const T& rhs, const A& lhs) {
return lhs.a == rhs;
}
int main() {
A a1, a2;
B b1, b2;
auto c1 = a1 == a2;
auto c2 = b1 == b2; //works now
auto c3 = b1 == b2;
}
Working demo.
Or with C++20 use requires
bool operator==(const A& lhs, const A& rhs) { return lhs.a == rhs.a; }
template <typename T> bool operator==(const A& lhs, const T& rhs)
requires (!std::is_same_v<T, B>)
{
return lhs.a == rhs;
}
template <typename T>bool operator==(const T& rhs, const A& lhs)
requires (!std::is_same_v<T, B>)
{
return lhs.a == rhs;
}
Demo
|
74,327,569
| 74,327,604
|
Error C++: no operator matches these operands. operand types are: std::ostream << void
|
I'm getting the error in my GetInfo() method:
void Quadrangle::GetInfo() {
cout << "Area = " << GetArea() << endl;
cout << GetPerimeter() << endl; //!!!error: no operator matches these operands. operand types are: std::ostream << void
}
double Quadrangle::GetArea() {
return 1.0 / 2 * (d1 * d2 * sin(angle * (M_PI / 180)));
}
void Quadrangle::GetPerimeter() {
cout << "Not enough information provided to calculate a perimeter for a quadrangle" << endl;
}
I get that this error occurs since GetPerimeter() is of type void. However, I am not sure if I can overload the insertion operator in this case to fix this error.
|
You are trying to output a message twice. You are trying to output the message from the GetPerimeter function.
void Quadrangle::GetPerimeter() {
cout << "Not enough information provided to calculate a perimeter for a quadrangle" << endl;
}
And you are trying to output the return value of GetPerimeter
cout << GetPerimeter() << endl;
But GetPerimeter does not return anything (it's a void function) so you cannot output it's return value.
The simple answer is to just output your message from the GetPerimeter function. So replace
cout << GetPerimeter() << endl;
with
GetPerimeter();
The alternative (which doesn't make much sense to me) would be to return that string that you want to output from GetPerimiter, like this
string Quadrangle::GetPerimeter() {
return "Not enough information provided to calculate a perimeter for a quadrangle";
}
and now this works because GetPerimeter does return something.
cout << GetPerimeter() << endl;
|
74,327,782
| 74,327,982
|
How can I find the number of scores entered by a user are greater than 80?
|
I have been trying to code a program that takes input from the user for scores and then calculated the average with an input validation. The only thing I am unable to figure out is how to tell the number of scores entered which are greater than 80. Also I have to do this without using arrays.
Here's what I currently have but is not working and starts the counter from 5 instead of 1 and then incrementing it as the scores greater than 80 are entered.
int main()
{
int score, sum=0, greater=0;
for(int i=1; i<=5; i++)
{
cout<<"Enter the score: "; //take user input for scores
cin>>score;
if(score>80)
{
for (int i=1; i<=5; i++){
greater= greater+1;
}
cout<<"There are "<<greater<<" number more than 80";
}
while (! (score >=0 && score <= 100 )) //input validation
{
cout << "Invalid Input. Enter the score between the range 0 - 100" << endl;
cout << "Enter the score: ";
cin >> score;
}
sum = sum + score;
}
float avg;
avg = sum/5.0; //calculating the average
cout<<"Average of scores: "<<avg<<endl;
Can anybody help me with this? It would be much appreciated.
Thanks!
I tried the above listed code and also tried to tweak it but it still shows the count as multiple of 5.
|
You mixed up the sequence of statements in your code.
Strong hint: If you write comments, then you will avoid such problems.
Please see below your corrected code
#include <iostream>
#include <limits>
using namespace std;
int main() {
int score, sum = 0, greater = 0;
// Get 5 values from user
for (int i = 0; i < 5; i++)
{
// We ant to validate the input and use the below to indicate the result
bool validValue = false;
// Now read values, until we get a valid one
do {
// We initially assume that the value is good
validValue = true;
// Get user input
cout << "\n\nEnter a score. Valid values are 0...100: "; //take user input for scores
cin >> score;
// Check, if the user entered some ivalid data like "abc"
if (!cin) {
validValue = false;
// Reset error flag from cin
cin.clear();
// Discard the rest of invalid characters taht are still in the input stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
}
// Check for valid range
else if (score < 0 or score > 100)
// Problem. Indicate
validValue = false;
if (not validValue)
std::cout << "\nError: Invalid value given. Please try again\n";
// contiinue the loo, until we get a valid value
} while (not validValue);
// Ok, now we have a valid value
// Check, if the score meets our condition
if (score > 80)
// Then counte up
greater = greater + 1;
// Calculate the overall sum, so that we can evaluate the average later
sum = sum + score;
}
// So, now we have read 5 values
// Calculate the avarage of all scores
double avg;
avg = sum / 5.0; //calculating the average
// And now show the result on the screen
cout << "There are " << greater << " number more than 80\n";
cout << "Average of scores: " << avg << '\n';
}
|
74,327,997
| 74,328,332
|
c++ No instance of overloaded function "std::async" matches argument list
|
i'm trying to run a listener Method async with std::async but i get the following error: No instance of overloaded function "std::async" matches argument list
auto listener = std::async(std::launch::async, server.Listen());
The server.Listen() returns void (nothing)
I've already read throu https://en.cppreference.com/w/cpp/thread/async for reference.
template< class Function, class... Args >
std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...>>
async( std::launch policy, Function&& f, Args&&... args );
template< class Function, class... Args >
std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...>>
async( std::launch policy, Function&& f, Args&&... args );
I'm using C++20 with CMAKE.
The full main.cpp Code:
#include <iostream>
#include <future>
#include <string>
#include <stdio.h>
#include "../<redacted>/IPC/UnixSocket/Server.h"
// https: // github.com/MikeShah/moderncppconcurrency/blob/main/async_buffer.cpp
int main()
{
printf("Hello World from <redacted>.Demo.IPCServer!\n");
<redacted>::IPC::UnixSocket::Server server(1556, SOCK_STREAM, INADDR_ANY);
auto listener = std::async(std::launch::async, server.Listen());
return 0;
}
i also get an intellisense issue on all the std::async or std::future types: <error-type> - i don't know if this might also be an indicator for something.
Can someone help?
|
Solution
thanks y'all for your answers, both solutions worked!
and also thanks for the comment on the <redacted> 'practice'
the working code:
auto listener = std::async(
std::launch::async,
&myprojectlibrary::IPC::UnixSocket::Server::Listen,
std::ref(server)
);
auto listener = std::async(
std::launch::async,
[&]{ server.Listen(); }
);
|
74,328,144
| 74,346,658
|
c++ ole automation how to clear excel cell contents
|
I am using the following function call of IDispatch interface to successfully write Hello World! to a cell in excel sheet excel.
LPOLESTR ptName = L"Value"; //What is the key for clearing the cell contents?
DISPID dispID;
xlCell->GetIDsOfNames(IID_NULL, &ptName, 1, LOCALE_USER_DEFAULT, &dispID);
LCID lcid = GetUserDefaultLCID();
std::wstring cellVal = L"Hello World!";
VARIANT vArgArray[1];
vArgArray[0].vt = VT_BSTR,
vArgArray[0].bstrVal = SysAllocString(cellVal.c_str());
DISPID dispidNamed = DISPID_PROPERTYPUT;
DISPPARAMS dp = {NULL, NULL, 0, 0};
dp.cArgs = 1;
dp.rgvarg = vArgArray;
dp.cNamedArgs = 1;
dp.rgdispidNamedArgs = &dispidNamed;
xlCell->Invoke(
dispID,
IID_NULL,
lcid,
DISPATCH_PROPERTYPUT,
&dp,
NULL,
NULL,
NULL);
Now I need to clear a cell using the same IDispatch interface (xlCell)
What value should I use for the LPOLESTR type variable (2nd parameter in GetIDsOfNames function) to initialize the dispID to successfully clear the cell by calling Invoke?
|
While I could not find the unique DISPID for clearing a cell/cell range, the thing that did work was to modify the VARIANT passed to the Invoke().
All I did was to change the VARIANT from this
vArgArray[0].vt = VT_BSTR,
vArgArray[0].bstrVal = SysAllocString(cellVal.c_str());
to this
vArgArray[0].vt = VT_EMPTY;
Hope it helps someone.
|
74,328,372
| 74,328,460
|
Is there any difference between `inline constexpr bool` and `concept`
|
template<typename T>
inline constexpr bool is_int_v1 = std::is_same_v<T, int>;
template<typename T>
concept is_int_v2 = std::is_same_v<T, int>;
In this code block whats the difference between the inline constexpr bool format and the concept format.
Is one better over the other or are they equivalent?
|
There are many differences. Variables are variables; even if they are inline constexpr, they are still variables. They represent objects and you can take their addresses.
A concept is not a variable at all. You cannot take its address or do anything of the kind with it. concepts get special grammatical rules like void func(ConceptName auto x); that variables do not.
Variables can be templates and get to undergo template specialization. concepts don't get to be specialized; this is deliberate. A specific concept name is associated with exactly one constraint expression no matter what template arguments are given to it.
But the most important difference is that concepts get to follow special subsumption rules during instantiation.
When you attempt to instantiate a template that is constrained, C++ goes through a number of steps to determine which of the matching templates is the "most constrained" version that could be applied. The most constrained form is given greater weight during the resolution of which template to instantiate.
std::signed_integral<T> is defined in terms of std::integral<T>.
template<class T>
concept signed_integral = integral<T> && is_signed_v<T>;
This means that, if some type T satisfies signed_integral, then it necessarily satisfies integral. If you have two versions of the same template, one constrained with integral and one with signed_integral, then passing unsigned int will necessarily instantiate the first.
int satisfies both concepts. But since the compiler knows that signed_integral contains integral, it is considered "more constrained". And therefore, that template is given priority if a type fulfills both.
That only happens if you use a concept. If these were just inline constexpr variables, then attempting to use int would get a compile error since both constraints are given equal weight.
inline constexpr variables are essentially black boxes to the constraint system. concepts are part of the constraint system.
|
74,328,526
| 74,328,547
|
Write a C++ program which will print (half pyramid) pattern of natural numbers
|
The task:
Write a C++ program which will print (half pyramid) pattern of natural numbers.
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
I have tried using this code, but its not giving the output:
#include <iostream>
using namespace std;
int main()
{
int rows, i, j;
cout << "Enter number of rows: ";
cin >> rows;
for(i = 1; i <= rows; i++)
{
for(j = 1; j <= i; j++)
{
cout << j << " ";
}
cout << "\n";
}
return 0;
}
OUTPUT:
Enter number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
|
j in your inner loop is the 1 based index of the element in the current row (1,2,3 etc.).
Instead of printing it, you should print a counter that is increased over all the iterations.
Something like:
#include <iostream>
int main()
{
int rows, i, j;
std::cout << "Enter number of rows: ";
std::cin >> rows;
int n = 1;
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= i; j++)
{
std::cout << n << " ";
n++; // for next iteration
}
std::cout << "\n";
}
return 0;
}
Output example:
Enter number of rows: 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
A side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
|
74,328,792
| 74,329,048
|
C++ reset locale to state at program start?
|
I crawled the web a lot and got not, what I searched for even not in SO. So I consider this a new question:
How to reset the locale settings to a state when the program is starting (e.g. first after main()) ?
int
main( int argc, char **argv )
{
// this is start output I like to have finally again
std::cout << 24500 << " (start)\n";
// several modifications ... [e.g. arbitrary source code that cannot be changed]
std::setlocale( LC_ALL, "" );
std::cout << 24500 << " (stage1)\n";
std::locale::global( std::locale( "" ) );
std::cout << 24500 << " (stage2)\n";
std::cout.imbue( std::locale() );
std::cout << 24500 << " (stage3)\n";
std::wcerr.imbue( std::locale() );
std::cout << 24500 << " (stage4)\n";
// end ... here goes the code to reset to the entry-behaviour (but won't work so far)
std::setlocale( LC_ALL, "C" );
std::locale::global( std::locale() );
std::cout << 24500 << " (end)\n";
return 0;
}
Output:
24500 (start)
24500 (stage1)
24500 (stage2)
24.500 (stage3)
24.500 (stage4)
24.500 (end)
The line with the "(end)" should show the same number formatting as "(start)" ...
Does anyone know how (in a general! portable?) way ?
|
A few points to start with:
calls to std::setlocale do not affect C++ iostream functions, only C functions such as printf;
calls to std::locale::global only change what subsequent calls to std::locale() return (as far as I understand it), they do not directly affect iostream functions;
your call to std::wcerr.imbue does nothing since you don't use std::wcerr afterward.
To change how std::cout formats things, call std::cout.imbue. So this line at the end should work:
std::cout.imbue( std::locale("C") );
You can also reset the global locale, but that isn't useful unless you use std::locale() afterward (without arguments). This would be the line:
std::locale::global( std::locale("C") );
You can also do both in order (note no "C" in the imbue call):
std::locale::global( std::locale("C") );
std::cout.imbue( std::locale() );
|
74,329,127
| 74,389,104
|
(Clang Error) compilation error: ld: library not found for -lcrt0.o. Any ideas?
|
The full terminal output is as follows:
>g++ -std=c++98 -static mainP1.o -o mainP1
>
>ld: library not found for -lcrt0.o
>
>clang: error: linker command failed with exit code 1 (use -v to see invocation)
>
>make: *** [mainP1] Error 1
I'm on a 2020 MacBook Pro with an intel CPU using Visual Studio Code. When I write basic OOP programs in C++ it compiles fine without any clang errors. However, when working with big OOP programs with multiple classes inheriting from a base class I would get this error.
I tried searching online for solutions, but no solution or explanation was found. I double-checked my makefile to ensure I was not linking classes incorrectly.
I thought maybe I should just dual-boot with UBUNTU Linux to avoid this weird XCODE issue I was encountering with clang, but that was also a fruitless endeavor.
|
The problem was my compiler path in Visual Studio Code.
I changed it to clang++, and now all my code compiles and executes without any problems.
How I changed it:
CMD + SHIFT + P
Typed in: C/C++: Edit Configurations (UI)
Made sure that "Mac" was selected under configuration name.
Changed Compiler Path to: /usr/bin/clang++
|
74,329,440
| 74,329,879
|
Divisors of a number with exactly 4 divisors
|
I have a number n (0 < n < 2 * 10^18), and I am given that it has exactly 4 divisors.
Is there a way I could get those divisors faster than O(sqrt(n)) ?
Using a classical algorithm to find divisors of a number (link) takes O(sqrt(n)) time. sqrt(2*10^18) is around 10^9 and it would take too much time.
Also a number with exactly 4 divisors is a product of two different prime numbers, or a cube of a prime number.
|
Pollard's rho method is simple, and takes expected O(sqrt(sqrt(n)) time. sqrt(sqrt(1018)) is < 32000, so quite fast for numbers in that range.
|
74,329,448
| 74,329,670
|
Reusing of std::unique_lock instead of creating a new one
|
One way to use std::unique_lock is
while (!m_exit || !m_queueOfTasks.empty())
{
std::unique_lock<std::mutex> ul(m_mutex);
std::cout << "Thread " << std::this_thread::get_id() << " is ready" << std::endl;
m_cond.wait(ul, [this]() {return !m_queueOfTasks.empty(); });
std::function<void()> work(std::move(m_queueOfTasks.front()));
m_queueOfTasks.pop_front();
std::cout << "Thread " << std::this_thread::get_id() << " got a new task" << std::endl;
ul.unlock();
work();
}
We could reuse the unique_lock instead of creating it every iteration.
Since its constructor
Constructs a unique_lock with m as the associated mutex. Additionally
locks the associated mutex by calling m.lock().
It means that we need to create it unlocked and lock it manually. Is it the correct code or I missed anything?
std::unique_lock<std::mutex> ul(m_mutex, std::defer_lock);
while (!m_exit || !m_queueOfTasks.empty())
{
ul.lock();
std::cout << "Thread " << std::this_thread::get_id() << " is ready" << std::endl;
m_cond.wait(ul, [this]() {return !m_queueOfTasks.empty(); });
std::function<void()> work(std::move(m_queueOfTasks.front()));
m_queueOfTasks.pop_front();
std::cout << "Thread " << std::this_thread::get_id() << " got a new task" << std::endl;
ul.unlock();
work();
}
The question is rather technical than an attempt of optimization.
|
There is one thing that can break complex code if you use this pattern (but won't break your snippets): an exception being thrown.
Consider this:
// static variable, or more realistically a class member
static std::unique_lock<std::mutex> ul(m_mutex, std::defer_lock);
while (!m_exit || !m_queueOfTasks.empty())
{
ul.lock();
std::cout << "Thread " << std::this_thread::get_id() << " is ready" << std::endl;
m_cond.wait(ul, [this]() {return !m_queueOfTasks.empty(); });
// exception thrown!
std::function<void()> work(std::move(m_queueOfTasks.front()));
m_queueOfTasks.pop_front();
std::cout << "Thread " << std::this_thread::get_id() << " got a new task" << std::endl;
ul.unlock();
work();
}
// m_mutex might still be locked
If the lock is not just a local variable and anything throws an exception between lock() and unlock(), then the mutex stays locked.
It can also happen if the lock is a local variable but you also have a try-catch block:
std::unique_lock<std::mutex> ul(m_mutex, std::defer_lock);
while (!m_exit || !m_queueOfTasks.empty())
{
try {
ul.lock();
std::cout << "Thread " << std::this_thread::get_id() << " is ready" << std::endl;
m_cond.wait(ul, [this]() {return !m_queueOfTasks.empty(); });
// exception thrown!
std::function<void()> work(std::move(m_queueOfTasks.front()));
m_queueOfTasks.pop_front();
std::cout << "Thread " << std::this_thread::get_id() << " got a new task" << std::endl;
ul.unlock();
} catch(...) {
std::cout << "Exception thrown";
}
// m_mutex might still be locked
work();
}
These things can quickly happen when working on complicated code, and is one of the reasons using scopes (and RAII) is recommended. This potential bug cannot happen when using the scope:
while (!m_exit || !m_queueOfTasks.empty())
{
{
std::unique_lock<std::mutex> ul(m_mutex, std::defer_lock);
std::cout << "Thread " << std::this_thread::get_id() << " is ready" << std::endl;
m_cond.wait(ul, [this]() {return !m_queueOfTasks.empty(); });
// exception thrown!
std::function<void()> work(std::move(m_queueOfTasks.front()));
m_queueOfTasks.pop_front();
std::cout << "Thread " << std::this_thread::get_id() << " got a new task" << std::endl;
} // lock destructor always called
// m_mutex is unlocked no matter what
work();
}
|
74,329,729
| 74,329,745
|
How to pop all the string from stack and store them in string variable?
|
This code pop all the required strings from the stack. But i want to store those string elements in a final one string variable. How to do it?
#include <sstream>
#include <stack>
#include <string>
#include<iostream>
using namespace std;
int main()
{
istringstream iss("abdd hhh |post_exp| a * b / (c + d) ^ f - g |\\post_exp| anndd jjss");
stack <string> mudassir;
string subs;
while (iss >> subs) {
if (subs == "|post_exp|")
{
while (iss >> subs && subs.find("|\\post_exp|") == string::npos)
{
mudassir.push(subs);
}
}
}
while (!mudassir.empty()) {
mudassir.top();
mudassir.pop();
}
cout << endl;
return 0;
}
|
You're almost good, but in the while-loop you'd like to build the string. This can be done multiple ways, what I'd recommend is:
std::ostringstream oss;
while (!mudassir.empty()) {
oss << mudassir.top();
mudassir.pop();
}
// if you'd like it in a variable,
// std::string result = oss.str();
std::cout << oss.str() << std::endl;
|
74,329,761
| 74,330,171
|
infinite loop while trying to insert node before a node in singly linked list
|
I tried to insert a node before a given node by specifying the position of the node before which I want to insert the newnode. I got the data present inside that node's position and using a while loop, compared this data with each node's data till I reached the point where I was supposed to insert the node.
But when I tried displaying the elements using a while statement my program went into an infinte loop.I checked where the head node was pointing to and its to pointing to the first node of the singly list only.
Could someone please help me out?
#include <iostream>
#include<stdlib.h>
using namespace std;
void display(struct node *);
struct node{
int data;
struct node *next;
};
struct node *ptr,*head=NULL;
void insertt(struct node *head){ //insert function to insert node before a node
struct node *ptr1=head;
int pos,poss,value;
cin>>poss; //getting position and value
cin>>value;
pos=poss-1;
while(pos--){ //moving to that position
ptr1=ptr1->next;
}
struct node *ptr2=ptr1;
struct node *newnode = (struct node*)malloc(sizeof(struct node)); //creating new node for insertion
newnode->next=NULL;
newnode->data=value;
struct node *preptr;
preptr=ptr1;
int c=ptr2->data; //getting value present in that particular position(node) of the list
while(ptr1->data!=c){ //inserting before node
preptr=ptr1;
ptr1=ptr1->next;
}
preptr->next=newnode;
newnode->next=ptr1;
display(head);
}
void display(struct node *head){ //displaying linked list
struct node *ptr2=head;
while(ptr2!=NULL){
cout<<ptr2->data;
ptr2=ptr2->next;
}
}
int main()
{
int n,val,i;
cin>>n; //number of nodes
for(i=0;i<n;i++){ //node creation
cin>>val;
struct node *newnode = (struct node*)malloc(sizeof(struct node));
newnode->data=val;
newnode->next=NULL;
if(head==NULL){
ptr=head;
head=newnode;
}
else{
ptr=head;
while(ptr->next!=NULL){
ptr=ptr->next;
}
ptr->next=newnode;
}
}
insertt(head); //insertion
return 0;
}
|
Once you find ptr1, you set preptr and ptr2 to ptr1.
Then you get c = ptr2->data, which happens to be the same as ptr1->data.
And you go on and check while (ptr1->data != c), which is always false. So that bottom while loop does nothing
And you get to the last lines with preptr and ptr1 pointing to the same node n.
Now you make n->next (preptr->next) point to newnode, and newnode->next point to ptr1 (n): an infinite loop.
n newnode
-------- ---------
preptr ---> | c | | value |
ptr1 ---> -------- ---------
| next | ---> | |
| | <--- | next |
-------- ---------
void insertt(struct node *head) {
struct node *ptr1 = head;
int pos, poss, value;
cin >> poss;
cin >> value;
pos = poss - 1;
while (pos--) {
ptr1 = ptr1->next;
}
struct node *ptr2 = ptr1;
struct node *newnode = (struct node *) malloc(sizeof(struct node));
newnode->next = NULL;
newnode->data = value;
struct node *preptr;
preptr = ptr1; // ptr1, ptr2, and preptr point to the same node n
int c = ptr2->data; // c = ptr1->data too
while (ptr1->data != c) { // always false
preptr = ptr1;
ptr1 = ptr1->next;
}
preptr->next = newnode; // n->next = newnode
newnode->next = ptr1; // newnode-next = n
display(head);
}
|
74,329,770
| 74,329,838
|
Searching for a number in a given array using pointers
|
I need to create a program that searches for a user inserted number from an array using pointers. This is my current code
#include <iostream>
using namespace std;
void FindNumber(int *ptrArr, int size, int *ptr1) {
for (int *p = ptrArr; p < ptrArr + size; ++p) {
if (ptrArr[*p] == *ptr1) {
cout << "Number (" << *ptr1 << ") found in the array with an index of: " << *p;
break;
}
if (*p == size) {
cout << "No such number in given array\n";
}
}
}
int main () {
int numbers[10] = {5, 4, 7, 10, 24, 15, 8, 2, 9, 13};
int num;
cout << "What number do you want to search for?\n";
cin >> num;
FindNumber(numbers, sizeof(numbers) / sizeof(int), &num);
return 0;
}
The problem is with for loop, but I don't know what it is
Sometimes it finds the number with right index, sometimes it doesn't find it even though there is that particular number in the array, sometimes it finds the number but outputs the wrong index
What number do you want to search for?
7
No such number in given array
Number (7) found in the array with an index of: 2
What number do you want to search for?
5
No such number in given array
Tried changing the for loop on my own but no successo. Hoping for some help.
|
You have 2 small typos in your code.
-No need to index the array with "*p"
-The index need to be calculated by subtracting p from the original pointer.
Please see here the fixed code:
#include <iostream>
using namespace std;
void FindNumber(int* ptrArr, int size, int* ptr1) {
for (int* p = ptrArr; p < ptrArr + size; ++p) {
if (*p == *ptr1) {
cout << "Number (" << *ptr1 << ") found in the array with an index of: " << (p-ptrArr);
return;
}
}
cout << "No such number in given array\n";
}
int main() {
int numbers[10] = { 5, 4, 7, 10, 24, 15, 8, 2, 9, 13 };
int num;
cout << "What number do you want to search for?\n";
cin >> num;
FindNumber(numbers, sizeof(numbers) / sizeof(int), &num);
return 0;
}
|
74,330,197
| 74,330,735
|
c++ socket recv() not writing into buffer fully
|
I am using a client socket to make a HTTP call to retrieve an image. Even though the recv call receives 36791 bytes, the buffer only has 4 bytes in the response body (the BUFF_SIZE has been set to 50000 for testing purposes). I have tried to make subsequent calls to recv but 0 bytes are returned from the subsequent calls. Would appreciate any help to understand why the buffer does not contain the full response from the socket recv as expected.
|
Issue was due to null-terminated strings as pointed out by @dewaffled, used std::string(buffer, total) as a solution to create a string that allows embedded null characters inspired by this post
|
74,330,204
| 74,331,016
|
How to get fstream to save to any windows desktop that opens the .exe in c++
|
I'm making a program for my brother that will display 50,000 proxie variations and will save them all to a .txt.
How can I make it so any windows machine that uses this code will get the .txt to save to the desktop.
Here's what I have:
fstream file;
file.open("proxies.txt", ios::out);
string line;
streambuf* stream_buffer_cout = cout.rdbuf();
streambuf* stream_buffer_cin = cin.rdbuf();
streambuf* stream_buffer_file = file.rdbuf();
cout.rdbuf(stream_buffer_file);
for (int i = 1; i < 50001; i++)
{
cout << n1 << i << n2 << "\n";
}
file.close();
Thanks for any help.
|
If I get what you are asking you just need to replace "proxies.txt" with an absolute path to a file in the desktop folder. You can get the desktop directory with the Win32 call SHGetFolderPath and put the path together using the standard (C++17) file system calls if you want, as below:
#include <iostream>
#include <filesystem>
#include <fstream>
#include <shlobj_core.h>
namespace fs = std::filesystem;
std::string desktop_directory() {
char path[MAX_PATH + 1];
if (SHGetFolderPathA(HWND_DESKTOP, CSIDL_DESKTOP, NULL,
SHGFP_TYPE_DEFAULT, path) == S_OK) {
return path;
} else {
return {}; // I'm not sure why this would fail...
}
}
int main() {
std::fstream file;
auto desktop_path = fs::path(desktop_directory()) / "proxies.txt";
file.open(desktop_path, std::ios::out);
// ...
file.close();
return 0;
}
|
74,330,255
| 74,330,341
|
Number of divisors from prime factorization
|
I am given prime factorization of a number as a map: std::map<int, int> m, where key is a prime number, and value is how many times this prime number occured in product.
Example: Prime factorization of 100 is 2 * 2 * 5 *5, so m[2] = 2, and m[5] = 2
My question is how can I get number of all divisors of a number given it's prime factorization (in the form as above)?
|
Number of divisors is simply equal to product of counts of every prime plus 1.
This comes from the fact that you can easily restore all divisors by having several nested loops iterating through all combinations of powers of primes. Every loop iterates through powers of single prime.
Number of different iterations of nested loops equal to product of sizes of all loops. And size of each loop is equal to prime count plus one, because you iterate through powers 0, 1, 2, ..., PrimeCnt, which has PrimeCnt + 1 numbers.
For example for 100 = 2 * 2 * 5 * 5 you have m[2] = 2 and m[5] = 2, hence you want to combine all powers of 2 with all powers of 5, i.e. combined 2^0 or 2^1 or 2^2 (here are 3 powers) with 5^0 or 5^1 or 5^2 (here are 3 powers), hence 3 powers multiplied by 3 powers gives 9.
This also can be easily verified by simple program below, which first computes all divisors as product of PrimeCnt + 1, and afterwards verifies this fact by computing all divisors through iteration.
You can easily put any number n and map of primes m into program below to verify other cases.
Try it online!
#include <iostream>
#include <map>
int main() {
int n = 100;
std::map<int, int> m = {{2, 2}, {5, 2}};
int c = 1;
for (auto [k, v]: m)
c *= v + 1;
std::cout << "Computed as product: " << c << std::endl;
int c2 = 0;
for (int i = 1; i <= n; ++i)
if (n % i == 0)
++c2;
std::cout << "Computed through iteration: " << c2 << std::endl;
}
Output:
Computed as product: 9
Computed through iteration: 9
|
74,330,356
| 74,330,733
|
Different results for overloaded templated equality comparison operator with C++20 between gcc and MSVC/clang
|
Consider the following implementation of equality operators, compiled with C++20 (live on godbolt):
#include <optional>
template <class T>
struct MyOptional{
bool has_value() const { return false;}
T const & operator*() const { return t; }
T t{};
};
template <class T>
bool operator==(MyOptional<T> const & lhs, std::nullopt_t)
{
return !lhs.has_value();
}
template <class U, class T>
bool operator==(U const & lhs, MyOptional<T> const & rhs)
{
// gcc error: no match for 'operator==' (operand types are 'const std::nullopt_t' and 'const int')
return rhs.has_value() ? lhs == *rhs : false;
}
int main(){
MyOptional<int> o1;
bool compiles = o1 == std::nullopt;
bool doesNotCompile = std::nullopt == o1; // gcc fails
}
Both clang 15 and MSVC 19.33 compile this without errors, but gcc 12.2 gives
<source>: In instantiation of 'bool operator==(const U&, const MyOptional<T>&) [with U = std::nullopt_t; T = int]':
<source>:26:43: required from here
<source>:20:34: error: no match for 'operator==' (operand types are 'const std::nullopt_t' and 'const int')
20 | return rhs.has_value() ? lhs == *rhs : false;
| ~~~~^~~~~~~
<source>:11:6: note: candidate: 'template<class T> bool operator==(const MyOptional<T>&, std::nullopt_t)' (reversed)
11 | bool operator==(MyOptional<T> const & lhs, std::nullopt_t)
| ^~~~~~~~
<source>:11:6: note: template argument deduction/substitution failed:
<source>:20:34: note: mismatched types 'const MyOptional<T>' and 'const int'
20 | return rhs.has_value() ? lhs == *rhs : false;
| ~~~~^~~~~~~
<source>:17:6: note: candidate: 'template<class U, class T> bool operator==(const U&, const MyOptional<T>&)' (reversed)
17 | bool operator==(U const & lhs, MyOptional<T> const & rhs)
| ^~~~~~~~
<source>:17:6: note: template argument deduction/substitution failed:
<source>:20:34: note: 'const std::nullopt_t' is not derived from 'const MyOptional<T>'
20 | return rhs.has_value() ? lhs == *rhs : false;
|
gcc apparently thinks that the second overload is a better match for std::nullopt == o1 and attempts to call it.
To me, it is not clear which compiler is right.
C++20 introduced the automatic reversal of the arguments when comparing for equality.
As far as I understand it, when the compiler sees std::nullopt == o1, it also considers o1 == std::nullopt.
However, I failed to find a statement anywhere when the reversed order of arguments is considered:
Should the compiler first search for valid calls for std::nullopt == o1, and if it found any, use it directly and never search for o1 == std::nullopt? In this case, I guess, gcc would be right?
Or, should the compiler always consider both std::nullopt == o1 and the reversed arguments o1 == std::nullopt, and from the set of viable functions select the "best" match (whatever "best" means here if the original and reversed arguments match different overloads)? I guess, in this case MSVC and clang are right?
So, the question is: Which compiler is right, and when in the matching process is the reversed order of arguments considered?
|
The rewritten candidates are considered at the same time as the non-rewritten ones. There is only a late tie breaker in the overload resolution rules if neither candidate is better by the higher priority rules. (See [over.match.best.general]/2 for the full decision chain.)
A candidate is considered better than another if at least one conversion sequence of an argument to a parameter is considered better than for the other candidate and none are considered worse. In your case all conversion sequences are equally good.
So the tie breakers need to be considered. The next relevant tie breaker before the one considering whether the candidate is a rewritten one, is partial ordering of templates from which the candidates were formed (applying here since both candidates come from templates).
Partial ordering of templates considers whether or not one template is more specialized than the other, which basically asks whether the set of argument lists accepted by one template is a strict subset of that of the other one. (The actual rules are quite complicated.)
So the question here is which templates exactly should be compared for this? If we just compare the two templates as you have written them, then neither is more specialized. But if we consider that one candidate was rewritten from the template, then probably this test should also consider the parameters of the template to be reversed? With that being the case, the first template would be more specialized, because it only accepts one type as its first argument, while the other accepts any type. And so the first template should be chosen.
If we do not consider this reversing, then we would fall through to the tie breaker considering rewriting and because the first template had to be rewritten to be a candidate for the operator, the second one would be chosen.
Clang and MSVC are following the reversing for partial ordering, while GCC is not.
This is CWG 2445 which was resolved to state that this reversing should be done, so that Clang and MSVC are correct. GCC seems to not have implemented the defect report yet.
|
74,330,447
| 74,330,597
|
I want to use my own random function with std::shuffle, but it is not working
|
I get an error when I use myRand::RandInt instead of something like default_random_engine. But I don't understand how am I supposed to implement the random_engine function. What I've done works well with std::random_shuffle, but I understand that this function was deprecated, and std::shuffle is preffered.
i am trying to get this to work:
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::shuffle (v.begin(), v.end(), myRand::RandInt);
return 0;
}
i've defined a namespace to implement the funcions:
namespace myRand{
bool simulatingRandom = false;
std::vector<int> secuenciaPseudoRandom = {1,0,1,0};
long unsigned int index = 0;
int Rand() {
//check
if (index > secuenciaPseudoRandom.size() - 1 ) {
index = 0;
std::cout << "Warning: myRand resetting secuence" << std::endl;
};
if (simulatingRandom) {
//std::cout << "myRand returning " << secuenciaPseudoRandom[i] << std::endl;
return secuenciaPseudoRandom[index++];
}
else {
return rand();
}
}
// works as rand() % i in the case of simulatingRandom == false
int RandInt(int i) {
return Rand() %i;
}
}
Basically I want to be able to change between simulating random and true random easily for testing purposes. So that in my main code I can do the testing with simulatingRandom set to true and then change it to false. Maybe there is a better way to do testing of functions that involves random. If so, I am open to any suggestions.
|
the last argument to std::shuffle must meet the requirements of UniformRandomBitGenerator. The generator should be an object not a function. For example a minimal implementation would be:
struct RandInt
{
using result_type = int;
static constexpr result_type min()
{
return 0;
}
static constexpr result_type max()
{
return RAND_MAX;
}
result_type operator()()
{
return Rand();
}
};
You can then call it as:
std::shuffle (v.begin(), v.end(), myRand::RandInt());
Note that you'l need to adjust the values of min and max if you set your simulatingRandom value to true to match the expected values. If they don't match the true values std::shuffle probably wont be as random as it should be.
Have to finish with the usual reminder not to use rand in modern code: Why is the use of rand() considered bad? especially without calling srand first. The use of rand is the main reason std::random_shuffle is deprecated.
|
74,330,859
| 74,340,347
|
If I link foo.so to bar.so, do private shared library dependencies need to be found at compile time?
|
Using cmake language, say I create a target foo, and link it to libbar.so. libbar.so was already compiled on a different platform with a cmake PRIVATE depedency on libbaz.so. So the dependency chain is
foo ----> libbar --(PRIVATE)--> libbaz
Does libbaz.so need to be present on the system when I compile foo and link it with libbar? My understanding is that I can compile and link foo without libbaz, and then find libbaz at foos runtime on a different platform using LD_LIBRARY_PATH. In other words, my hunch is that libbaz is only a runtime, and not compile time dependency.
But my current design for a large build system is dependent on this hunch being correct, so I want to double check.
|
General linking by the compiler toolchain
In general it depends on how libbaz got linked to libbar.
If libbaz got statically linked when building libbar then there are no compile or runtime dependencies at build-time of foo to libbaz. This is due to the fact that statically linked code gets "copied" into the file that links it (when no special hacks or other dark magic is used).
If libbaz got dynamically linked when building libbar then libbaz is (only) a runtime dependency at build-time of foo.
final library
linking
middle library
linking
first library
runtime dependencies
foo
statically
libbar
statically
libbaz
none
foo
statically
libbar
dynamically
libbaz
libbaz
foo
dynamically
libbar
statically
libbaz
libbar
foo
dynamically
libbar
dynamically
libbaz
libbar, libbaz
There is an exception. But it should not apply in your specified scenario. If libbar dynamically loads another library (like libbaz) via Windows-API LoadLibrary or Unix/Linux/...-API dlopen then the linker does not have any information about this dependency at build-time. In this case it is a dynamic runtime dependency by code.
Public / Private
In this case as you are using CMake it is a terminology of CMake. This is only meaningful when defining dependencies in CMake (mainly via target_link_libraries).
CMake target
linking
CMake target or library
description
libbar
private
libbaz
libbar gets libbaz' includes, etc. at compile-time and as linking library at link-time.
libbar
public
libbaz
libbar gets libbaz' includes, etc. at compile-time and as linking library at link-time.Libraries using libbar are also getting the interface portion of libbaz (interface includes, libs, etc.).
libbar
interface
libbaz
libbar does not use libbaz at all.Libraries using libbar are getting the interface portion of libbaz (interface includes, libs, etc.).
|
74,330,881
| 74,330,937
|
Check if two arrays have same values(they may be with different indexes) c++
|
Good evening!
I have a task: implement any function to sort array and then check if two arrays(the input and the output) are the same(meaning that the values are the same). Values in array are random, so there my be something like [5,2,5,5,6,-1,3,0,84305]
I was thinking about checking if elements are in both arrays, then if yes - assign them to some rubbish value(I was hoping to go for NULL, but apparently it works only in Python), and then if any array has something that is not our rubbish value return false, but I am not sure about this variant, maybe someone has better ideas? That would be very helpful
|
If the values are unique, insert all values from the first array in an std::unordered_set and remove all values from the second array from it. If your set is empty at the end, or if any removal fails, then the sets aren't "equal" as per your definition.
If the values aren't unique, you'll need to use an std::unordered_map with the value the count of times that particular value was seen. When inserting, you increment the value (or set to 1 if it's the first time you've seen it). When removing, you decrement it. The sets aren't "equal" if you can't find an entry to do the removal step, or if there's any value in the map that's not 0.
|
74,331,244
| 74,331,347
|
How to insert element using template
|
I have some doubts about my insert method. it is compiling, but with no result. I presume that it is containing some coding errors. Can you help me resolving this? Thanks in advance.
private:
T* elements;
int capacity;
int nbElements;
template <class T>
void TableDynamic<T>::insert(const T& element, int index)
{
int *temp = new int[capacity] ;
for(int i =0; i<nbElements; i++)
{
temp[i] = element;
}
delete[] elements;
int *elem = new int[capacite];
}
|
I have written some code for you. see if its works for you.
#include <iostream>
using namespace std;
// insert element using template
template <class T>
class TableDynamic
{
private:
T *elements;
int capacity;
int nbElements;
public:
TableDynamic(int capacity)
{
this->capacity = capacity;
this->nbElements = 0;
this->elements = new T[capacity];
}
void insert(const T &element, int index)
{
if (index < 0 || index > nbElements)
{
cout << "Index out of range" << endl;
return;
}
if (nbElements == capacity)
{
cout << "Table is full" << endl;
return;
}
for (int i = nbElements; i > index; i--)
{
elements[i] = elements[i - 1];
}
elements[index] = element;
nbElements++;
}
void print()
{
for (int i = 0; i < nbElements; i++)
{
cout << elements[i] << " ";
}
cout << endl;
}
};
int main()
{
TableDynamic<int> table(10);
table.insert(10, 0);
table.insert(20, 1);
table.insert(30, 2);
// print the table
table.print();
return 0;
}
|
74,331,324
| 74,331,407
|
C++ Is it right to use constexpr in size declaration
|
I'm trying to make sizes declaration is it right to use constexpr
#define BYTE ((size_t)1)
#define KIB (constexpr BYTE * (size_t)1024)
#define MIB (constexpr KIB * (size_t)1024)
#define GIB (constexpr MIB * (size_t)1024)
|
The constexpr keyword can't be used as part of an expression. It just makes no syntactical sense in the position you are using it. constexpr is a qualifier on a declaration for a variable or function.
There is no point in using a macro like this. You can declare these constants as constexpr variables:
constexpr size_t BYTE = 1;
constexpr size_t KIB = BYTE * 1024;
constexpr size_t MIB = KIB * 1024;
constexpr size_t GIB = MIB * 1024;
You don't even need the constexpr. It will work with just const instead exactly the same. However constexpr makes the intention of these being compile-time constants clearer and will avoid making mistakes causing them not to be compile-time constants.
Also, the explicit casts to size_t are not needed. Usual arithmetic conversions will make sure that the second operand is converted to size_t as well. (I suppose technically it is allowed for size_t to have lower rank than int, in which case it may be a problem, which however can be avoided by using unsigned literals 1024U instead of signed int. But if we are talking about weird platforms like that size_t might also be too small to hold the values you want to compute here.)
Since C++17 it is slightly safer to additionally qualify the variables with inline. This has the effect of giving the variables external linkage while still making it possible to define them in multiple translation units. Otherwise they have internal linkage, which usually is not a problem, however one might take the address of the variable and use it e.g. in the definition of an inline function. Then having internal linkage for the variable would cause an ODR violation on the inline function definition.
|
74,331,660
| 74,331,714
|
How does typename assignment work in C++ (typename =)?
|
I came across this example when looking at std::enable_if:
template<class T,
typename = std::enable_if_t<std::is_array<T>::value> >
void destroy(T* t)
{
for(std::size_t i = 0; i < std::extent<T>::value; ++i) {
destroy((*t)[i]);
}
}
In template argument lists, you can put untemplated classes/structs. So the above code is still possible when we remove the typename =. What does the typename = in this code mean and do?
|
The typename on the 2nd template argument indicates the argument is a type rather than a constant value. The argument has no name specified, but the = indicates it has a default type if the caller doesn't specify one. In this case, that type is the result of enable_if_t<...> (aka std::enable_if<...>::type).
std::enable_if has 2 template arguments. The 1st argument takes in a boolean constant, and the 2nd argument specifies the type of the std::enable_if<...>::type member. The 2nd argument is void by default. The type member is defined only when the boolean is true, otherwise it is undefined when the boolean is false. In this case, that boolean is the result of std::is_array<T>::value.
So, if T is an array type, std::is_array<T>::value will be true, thus std::enable_if<true, void>::type will be void, and the final template will be:
template<class T, typename _ = void>
void destroy(T* t)
{
...
}
Otherwise, if T is not an array type, std::is_array<T>::value will be false, thus std::enable_if<false, void>::type will be undefined, and the final template will be:
template<class T, typename _ = [undefined] >
void destroy(T* t)
{
...
}
And thus the template will be disabled since it is invalid.
|
74,331,876
| 74,331,917
|
How to make a data member const after but not during construction?
|
Without relying on const_cast, how can one make a C++ data member const after but not during construction when there is an expensive-to-compute intermediate value that is needed to calculate multiple data members?
The following minimal, complete, verifiable example further explains the question and its reason. To avoid wasting your time, I recommend that you begin by reading the example's two comments.
#include <iostream>
namespace {
constexpr int initializer {3};
constexpr int ka {10};
constexpr int kb {25};
class T {
private:
int value;
const int a_;
const int b_;
public:
T(int n);
inline int operator()() const { return value; }
inline int a() const { return a_; }
inline int b() const { return b_; }
int &operator--();
};
T::T(const int n): value {n - 1}, a_ {0}, b_ {0}
{
// The integer expensive
// + is to be computed only once and,
// + after the T object has been constructed,
// is not to be stored.
// These requirements must be met without reliance
// on the compiler's optimizer.
const int expensive {n*n*n - 1};
const_cast<int &>(a_) = ka*expensive;
const_cast<int &>(b_) = kb*expensive;
}
int &T::operator--()
{
--value;
// To alter a_ or b_ is forbidden. Therefore, the compiler
// must abort compilation if the next line is uncommented.
//--a_; --b_;
return value;
}
}
int main()
{
T t(initializer);
std::cout << "before decrement, t() == " << t() << "\n";
--t;
std::cout << "after decrement, t() == " << t() << "\n";
std::cout << "t.a() == " << t.a() << "\n";
std::cout << "t.b() == " << t.b() << "\n";
return 0;
}
Output:
before decrement, t() == 2
after decrement, t() == 1
t.a() == 260
t.b() == 650
(I am aware of this previous, beginner's question, but it treats an elementary case. Please see my comments in the code above. My trouble is that I have an expensive initialization I do not wish to perform twice, whose intermediate result I do not wish to store; whereas I still wish the compiler to protect my constant data members once construction is complete. I realize that some C++ programmers avoid constant data members on principle but this is a matter of style. I am not asking how to avoid constant data members; I am asking how to implement them in such a case as mine without resort to const_cast and without wasting memory, execution time, or runtime battery charge.)
FOLLOW-UP
After reading the several answers and experimenting on my PC, I believe that I have taken the wrong approach and, therefore, asked the wrong question. Though C++ does afford const data members, their use tends to run contrary to normal data paradigms. What is a const data member of a variable object, after all? It isn't really constant in the usual sense, is it, for one can overwrite it by using the = operator on its parent object. It is awkward. It does not suit its intended purpose.
@Homer512's comment illustrates the trouble with my approach:
Don't overstress yourself into making members const when it is inconvenient. If anything, it can lead to inefficient code generation, e.g. by making move-construction fall back to copy constructions.
The right way to prevent inadvertent modification to data members that should not change is apparently, simply to provide no interface to change them—and if it is necessary to protect the data members from the class's own member functions, why, @Some programmer dude's answer shows how to do this.
I now doubt that it is possible to handle const data members smoothly in C++. The const is protecting the wrong thing in this case.
|
One possible way could be to put a and b in a second structure, which does the expensive calculation, and then have a constant member of this structure.
Perhaps something like this:
class T {
struct constants {
int a;
int b;
constants(int n) {
const int expensive = ... something involving n...;
a = ka * expensive;
b = kb * expensive;
}
};
constants const c_;
public:
T(int n)
: c_{ n }
{
}
};
With that said, why make a_ and b_ constant in the first place, if you control the class T and its implementation?
If you want to inhibit possible modifications from other developers that might work on the T class, then add plenty of documentation and comments about the values not being allowed to be modified. Then if someone modifies the values of a_ or b_ anyway, then it's their fault for making possibly breaking changes. Good code-review practices and proper version control handling should then be used to point out and possibly blame wrongdoers.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.