ostringstream operator<< for long? - c++

$ uname -a
Darwin Wheelie-Cyberman 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386
$ g++ --version
i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ cat nolove.cc
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char ** argv) {
unsigned long long i = 0;
ostringstream o();
// Compiles fine
cout << i;
// Explodes, see below
o << i;
return 0;
}
$ g++ -o nolove nolove.cc
nolove.cc: In function ‘int main(int, char**)’:
nolove.cc:14: error: invalid operands of types ‘std::ostringstream ()()’ and ‘long long unsigned int’ to binary ‘operator<<’
I'm somewhat new to C++ (but not to programming or OO design, etc) so I'm assuming I'm just doing it wrong. In practice the unsigned long long above equates to an unsigned 64bit integer on my targeted platforms (above and g++ 4.4.1 on linux 2.6), a different type that amounted to the same thing would also be acceptable (but I haven't found any.)
Can I use an ostringstream to format this (or similar) type? If not, can I do it without dragging in stdio and snprintf? More philosophically, how does the typing work out that cout can do it, and why wasn't that functionality extended to the string stream stuff?

This is becuse this
ostringstream o();
doesn't declare a variable, but a function returning a stream.
Try this instead
ostringstream o;
See also
Most vexing parse: why doesn't A a(()); work?

Related

How to store a bi-directional graph using map in C++?

I am trying to store a bi-directional graph as an adjacency list using std::map<int,vector<int>>. The idea here is to store n nodes, from 1 to n in this map.
The input is given as u v, which denotes an edge between node u and node v. We get n such inputs on n lines.
My code for storing the graph:
int u,v;
map<int,vector<int>> graph();
for(int i=0;i<n;i++) {
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
This should work, but it gave me errors when complied with C++ 14. I then compiled this with C++ 17 and the errors still persists.
Errors(as displayed on my terminal):
/home/chirag/chiragC/forces/try.cpp: In function ‘void solve()’:
/home/chirag/chiragC/forces/try.cpp:68:10: warning: pointer to a function used in arithmetic [-Wpointer-arith]
graph[u].push_back(v);
^
/home/chirag/chiragC/forces/try.cpp:68:12: error: request for member ‘push_back’ in ‘*(graph + ((sizetype)u))’, which is of non-class type ‘std::map<int, std::vector<int> >()’
graph[u].push_back(v);
^~~~~~~~~
/home/chirag/chiragC/forces/try.cpp:69:10: warning: pointer to a function used in arithmetic [-Wpointer-arith]
graph[v].push_back(u);
^
/home/chirag/chiragC/forces/try.cpp:69:12: error: request for member ‘push_back’ in ‘*(graph + ((sizetype)v))’, which is of non-class type ‘std::map<int, std::vector<int> >()’
graph[v].push_back(u);
^~~~~~~~~
[Finished in 1.5s with exit code 1]
I feel the script I am using to store the graph is correct, as my friend was able to run this code completely fine on his system. I don't know why it is giving errors.
My System: debian 10
Headers used: #include<bits/stdc++.h>
Some info on my Compiler:
chirag#debian10:~/chiragC/forces$ ls /usr/bin | grep g++
arm-none-eabi-g++
avr-g++
g++
g++-8
x86_64-linux-gnu-g++
x86_64-linux-gnu-g++-8
chirag#debian10:~/chiragC/forces$ g++ --version
g++ (Debian 8.3.0-6) 8.3.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
chirag#debian10:~/chiragC/forces$
Your bug is that you are trying to make a function named graph() remove the parenthesis then all will be fine.

GCC Warning forming offset [X1, X2] is out of the bounds [0, X3]

I have the following code to copy one raw (not null terminated) string into const-size char array, but when I compile I get a warning. Could please someone help me to understand what's wrong with this peace of code?
#include <array>
#include <cstring>
char reason_[20];
template <size_t N>
void CopyStr(char(&out)[N], const std::string_view& in)
{
memcpy(out, in.data(), std::min(in.size(), N));
if (in.size() < N)
out[in.size()] = '\0';
}
int main()
{
CopyStr(reason_, "User request");
}
g++-8 -O3 -mavx -m64 -std=c++17 -g0 -DNDEBUG -fconcepts -Wall test.cpp
In function ‘void* memcpy(void*, const void*, size_t)’,
inlined from ‘void CopyStr(char (&)[N], const string_view&) [with long unsigned int N = 20]’ at test.cpp:9:11,
inlined from ‘int main()’ at test.cpp:16:12:
/usr/include/x86_64-linux-gnu/bits/string_fortified.h:34:33: warning: ‘void* __builtin_memcpy(void*, const void*, long unsigned int)’ forming offset [14, 20] is out of the bounds [0, 13] [-Warray-bounds]
return __builtin___memcpy_chk (__dest, __src, __len, __bos0 (__dest));
The following is output of g++-8 --version
g++ (GCC) 8.3.1 20190311 (Red Hat 8.3.1-3)
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
No warnings for
clang version 9.0.0-2 (tags/RELEASE_900/final)
Target: x86_64-pc-linux-gnu
No warnings for
g++ (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE

error using auto: does not name a type, c++ version of numpy's arange

Looking for code to implement numpy's arange function in c++, I found this answer.
I placed the following code in a file test_arange_c.cpp:
#include <vector>
template<typename T>
std::vector<T> arange(T start, T stop, T step = 1)
{
std::vector<T> values;
for (T value = start; value < stop; value += step)
values.push_back(value);
return values;
}
int main()
{
double dt;
dt = 0.5;
auto t_array = arange<double>(0, 40, dt);
return 0;
}
When I try to compile it, I get the following error:
$ c++ test_arange_c.cpp -o test_arange_c.out
test_arange_c.cpp: In function ‘int main()’:
test_arange_c.cpp:14:8: error: ‘t_array’ does not name a type
auto t_array = arange<double>(0, 40, dt);
Without doubt, I've made a mistake that will be obvious to seasoned c++ users. But, after searching Google for a while, I haven't come up with what it is.
As #Brian suggested, I had not enabled C++11 support.
$ c++ --version
c++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
This fails:
$ c++ test_arange_c.cpp -o test_arange_c.out
test_arange_c.cpp: In function ‘int main()’:
test_arange_c.cpp:16:8: error: ‘t_array’ does not name a type
auto t_array = arange<double>(0, 40, dt);
^
This works:
$ c++ -std=c++11 test_arange_c.cpp -o test_arange_c.out
$

Why is valgrind reporting errors for libstdc++'s std::locale?

Related question: wifstream with imbue, locale produces valgrind errors
I am using cppreference's (potentially flawed) examples, in particular the one present on their imbue page. Using the command line on the coliru online compiler:
clang++ -std=c++14 -stdlib=libstdc++ -O3 -Wall -Wextra -pedantic-errors
-pthread main.cpp && valgrind ./a.out
the following test cases produce errors like these (unless I state "no errors"):
==5421== Invalid read of size 8
==5421== at 0x590CBC0: wcscmp (wcscmp.S:208)
==5421== by 0x4EAC174: std::moneypunct<wchar_t, false>::~moneypunct() (monetary_members.cc:927)
==5421== by 0x4EAC1D8: std::moneypunct<wchar_t, false>::~moneypunct() (monetary_members.cc:932)
==5421== by 0x4EA1695: std::locale::_Impl::~_Impl() (locale_classes.h:412)
==5421== by 0x4EA17D8: std::locale::~locale() (locale_classes.h:521)
==5421== by 0x400955: main (in /tmp/1412433400.2497/a.out)
==5421== Address 0x5c2e0b8 is 0 bytes after a block of size 8 alloc'd
==5421== at 0x4C2AC27: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5421== by 0x4EABE61: std::moneypunct<wchar_t, false>::_M_initialize_moneypunct(__locale_struct*, char const*) (monetary_members.cc:847)
==5421== by 0x4EA3CD7: std::locale::_Impl::_Impl(char const*, unsigned long) (locale_facets_nonio.h:993)
==5421== by 0x4EA406A: std::locale::locale(char const*) (localename.cc:42)
==5421== by 0x40094D: main (in /tmp/1412433400.2497/a.out)
cppreference's imbue example:
#include <iostream>
#include <sstream>
#include <locale>
int main()
{
std::istringstream iss;
iss.imbue(std::locale("en_US.UTF8"));
std::cout << "Current locale: " << iss.getloc().name() << '\n';
iss.imbue(std::locale());
std::cout << "Global locale : " << iss.getloc().name() << '\n';
}
libstdc++ - errors
libc++ - no errors
The linked questioned at the top's reduced example:
#include <iostream>
#include <locale>
int main (int argc, char **argv) {
try {
std::locale * l1 = new std::locale("de_DE.UTF-8");
delete l1;
std::locale l2("de_DE.UTF-8");
} catch(...) {
return 0;
}
return 0;
};
libstdc++ - errors
libc++ - no errors
Linked bug report in above question's reduced example:
#include <wchar.h>
void foo(int)
{
}
int main()
{
wchar_t *a=new wchar_t[2], *b=new wchar_t[2];
size_t j;
a[0]=b[0]='A';
a[1]=b[1]=0;
foo(wcscmp(a, b));
delete[] a;
delete[] b;
return 0;
}
libstdc++ - no errors
libc++ - no errors
I've added the bug report's test case for completeness even though they produce no errors. Coliru's valgrind version is 3.7.0, and OP in the linked thread mentions upgrading to 3.8.1 and still receiving errors. I'm not on a Linux machine at the moment, and so cannot test it myself. If it makes any difference, here's glibc output:
GNU C Library (Ubuntu EGLIBC 2.15-0ubuntu10.7) stable release version 2.15, by Roland McGrath et al.
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
Compiled by GNU CC version 4.6.3.
Compiled on a Linux 3.2.60 system on 2014-08-28.
Available extensions:
crypt add-on version 2.1 by Michael Glad and others
GNU Libidn by Simon Josefsson
Native POSIX Threads Library by Ulrich Drepper et al
BIND-8.2.3-T5B
libc ABIs: UNIQUE IFUNC
For bug reporting instructions, please see:
<http://www.debian.org/Bugs/>.
Where does the bug lie? cppreference's examples, valgrind, or libstdc++?
It's a false positive in Valgrind, fixed here.

error: ‘unique_ptr’ is not a member of ‘std’

I guess it's pretty self explanatory - I can't seem to use C++11 features, even though I think I have everything set up properly - which likely means that I don't.
Here's my code:
#include <cstdlib>
#include <iostream>
class Object {
private:
int value;
public:
Object(int val) {
value = val;
}
int get_val() {
return value;
}
void set_val(int val) {
value = val;
}
};
int main() {
Object *obj = new Object(3);
std::unique_ptr<Object> smart_obj(new Object(5));
std::cout << obj->get_val() << std::endl;
return 0;
}
Here's my version of g++:
ubuntu#ubuntu:~/Desktop$ g++ --version
g++ (Ubuntu/Linaro 4.7.3-2ubuntu1~12.04) 4.7.3
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Here's how I'm compiling the code:
ubuntu#ubuntu:~/Desktop$ g++ main.cpp -o run --std=c++11
main.cpp: In function ‘int main()’:
main.cpp:25:2: error: ‘unique_ptr’ is not a member of ‘std’
main.cpp:25:24: error: expected primary-expression before ‘>’ token
main.cpp:25:49: error: ‘smart_obj’ was not declared in this scope
Note that I've tried both -std=c++11 and -std=c++0x to no avail.
I'm running Ubuntu 12.04 LTS from a flash drive on an Intel x64 machine.
You need to include header where unique_ptr and shared_ptr are defined
#include <memory>
As you already knew that you need to compile with c++11 flag
g++ main.cpp -o run -std=c++11
// ^
So here what I learned in 2020 - memory.h is at /usr/include AND in /usr/include/c++/4.8.5 and you need the second to be found before the first.
In Eclipse set the order using Project->Properties->Path and Symbols->Includes->Add... path if needed and set first
You need to include #include that will solve the problem, at least on my ubunto linux machine