[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

C++

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 198
Thread images: 12

File: cpp.png (62KB, 1385x1557px) Image search: [Google]
cpp.png
62KB, 1385x1557px
>language so good and fast that even if you write shit code it is still the fastest
Truly the best language, how can other languages even compete?
>>
>>60483918
>even if you write shit code it is still the fastest
Bad structure is still the main reason a program is slow.
>>
Other languages don't have pounds of annoying features thrown in by academics that nobody uses except for that one guy who just wants to make his code more obscure.

But if you're a good programmer you'll be smart enough not to use the entire language so its fine
>>
>>60483918
>how can other languages even compete?
by using the same backend
>>
>>60483953
C++ has a shit load of under utilised parts mainly because their case use is RARE not because they are useless

In my opinion there aren't enough common use stuff like string manipulation
>>
>he hasnt heard of pypy
>>
>c++
>good
Can it do this?
import sys

f = open(sys.argv[1], "r")
for line in f:
for n in line.split()[::-2]:
sys.stdout.write(n + " ")

print("");
>>
>>60484478
Stop comparing stdlibs instead of languages.
>>
>>60484463
>he think it's actually fast
>>
>>60484665
It's not his fault they are STANDARDIZED to come with the language.
>>
>>60484463
>pypy
>not total shit
summerfags
>>
>>60484478
You forgot to close the stream.
>>
>>60484720
Comparing stdlibs is relevant only for very small projects.
>>
>>60484806
Yeah, because all other libraries are OS wrappers.

Shit like that might fly if you write some pacman or some throwaway driver in C, but for actual software a good standard library is 33%.
>>
>>60484861
We don't write the same kind of softwares. In mines the stdlib is barely 5%
>>
File: 13000630851.png (106KB, 284x250px) Image search: [Google]
13000630851.png
106KB, 284x250px
>>60484888
>softwares
>>
>>60485430
I don't get it. Are you expecting an answer?
>>
Is pretending to be retarded the new meme or are imageboards really just completely overrun with retarded normies now?
>>
>>60483918

>>language so good and fast that even if you write shit code it is still the fastest
if you write shit code in C++ it'll crash and burn

I like the language but it's a fucking mess and it's full of gotchas.
>>
>>60484478
#include <iostream>
#include <fstream>
#include <deque>
#include <sstream>

int main (int argc, char **argv)
{
std::ifstream in(argv[1], std::ios::in | std::ifstream::binary);
std::string line;

while (std::getline(in, line))
{
std::deque<int> l;

std::istringstream linestream(line);
int number;
while (linestream >> number)
{
l.emplace_back(number);
}

for (auto it = l.end() - 1; it >= l.begin(); it -= 2)
{
std::cout << *it << " ";
}
std::cout << "\n";
}
}
>>
>>60484888
>We don't write the same kind of softwares. In mines the stdlib is barely 5%
There are some occasional cases where this is justified, but since we are on 4chinks I'm just assuming the worst that you are reimplementing the standard library in a poor way.

>>60485430
>>60485452
not me, since I'm not a korean kartoon poster
>>
>tfw move semantics and optimizatation flags mean you can write shit code and It'll copy elide and RVO it anyway
GOAT Lang
Good thing brainlets hate it
>>
>>60488019
Only with C++11, old code will stay shit with copies everywhere.
>>
>>60483918
Never understood the immense hate for C++. I find it pretty easy to program with. For GUI and other frontend stuff I just use Qt if I want to contaminate my code. If not I just use vxwidgets and other thirdparty libs.
>>
>>60485573
This is my take.

Think it's been said that takes like 10 years to write a c++ parser. That's insane, the language is too big.

Well you could say "yeah but most of it is never used", but because it exists somewhere, your going to run into it.
>>
>>60488019

>tfw too dumb to understand move semantics
>>
>>60488166
It's just taking the meat of a structure and leaving a skeleton. It's still a "valid" type but largely empty.
>>
>>60488271
wat
>>
>>60488294
A relevant example would be a vector of strings. In C++11, std::string has now a move constructor. Before that, a local string str you passed to vector::push_back() was actually copied into the new element, because std::string only had a copy constructor, even though you didn't have any use for str after the insertion.
Now, you either push_back(std::move(str)) or emplace_back(std::move(str)) in order to move the content of str into the vector instead of copying it.
The difference between emplace_back() and push_back() is only really visible in the case of inserting structures without move constructor, because emplace_back() tries to construct the new structure in-place, instead of copying the whole structure you would have to pass to push_back().
>>
>>60488596
And C has those things rights since 89. C++ is just repairing bad design choices.
>>
>>60488596

I still don't think I'll get it until I see pictures of what memory looks like whenever you're using this move semantics bollocks
>>
>>60488674
Not that C has those things, but it avoided the problem by having pointers as the only level of memory reference. Also, C standard lib doesn't have generic containers right out of the box, so the problem is on the responsibility of the programmer in this case.

>>60488753
#include <iostream>
#include <string>

int main(void)
{
std::string str1 = "hello, world!";
std::string str2;

std::cout << "str1 = \"" << str1 << "\"\n";
std::cout << "str2 = \"" << str2 << "\"\n";

str2 = std::move(str1);

std::cout << "--\n";
std::cout << "str1 = \"" << str1 << "\"\n";
std::cout << "str2 = \"" << str2 << "\"\n";

return 0;
}

which outputs
str1 = "hello, world!"
str2 = ""
--
str1 = ""
str2 = "hello, world!"
>>
>>60484478

Python-fags eternally BTFO

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>

using namespace std;

int main (int argc, char **argv)
{
ifstream in(argv[1], ios::in);
string line;

while (getline(cin, line))
{
istringstream ss(line);
vector<string> words(istream_iterator<string>{ss}, istream_iterator<string>());
copy_if(words.rbegin(), words.rend(), ostream_iterator<string>(cout, " "), [i=0](auto w) mutable { return i++ % 2 == 0; });
cout << '\n';
}
}
>>
>>60486047
What the fuck is this?
It doesn't do what >>60484478 does, which is to split line into whitespace separated words and then print every other word in reverse order (without reversing the letters in each word).

It looks like it might be an attempt to print every second character in each line backwards. But I don't think it will even do that much, owing to the reading of int at a time, rather than char.
>>
>>60489015
doesn't work
>>
>>60488981

I don't see the advantage of this.
You're copying the contents of str1 to str2...? What's the point?
>>
>>60489135
change cin to in, typo.

Or just use cin and pipe a file into it, like how a sensible program would work:

#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>

using namespace std;

int main (int argc, char **argv)
{
string line;

while (getline(cin, line))
{
istringstream ss(line);
vector<string> words(istream_iterator<string>{ss}, istream_iterator<string>());
copy_if(words.rbegin(), words.rend(), ostream_iterator<string>(cout, " "), [i=0](auto w) mutable { return i++ % 2 == 0; });
cout << '\n';
}
>>
>>60489135
Test here:

https://wandbox.org/permlink/nh30ehQsn5Xjk4Xt
>>
>>60489129
They actually do the same. You can't tell what type the python one targets because no static typing.
>>
>>60489156
just a note, don't use
using namespace std;

It's considered bad style, always give the namespace i.e. know where your functions come from.
>>
>>60489282

if any of the headers you're including are defining ::vector or ::cout, you need to torch them anyway.
>>
>>60484463
>what is GIL
>>
File: 1420761495662.png (1MB, 1200x1800px) Image search: [Google]
1420761495662.png
1MB, 1200x1800px
>>60489156
$ time ./a.out <in >/dev/null

real 0m2.609s
user 0m2.488s
sys 0m0.112s

>>60486047
$ time ./a.out in >/dev/null

real 0m1.147s
user 0m1.140s
sys 0m0.000s

>>60484478
$ time python py.py in >/dev/null

real 0m1.731s
user 0m1.384s
sys 0m0.008s

>python nearly as fast as c++
C++FAGS ON SUICIDE WATCH

(i used a list with 1.000.000 entries and 10 space seperated numbers on each line)

ALL HAIL PYTHON FASTEST SNAKE LANGUAGE IN THE WORLD
>>
>>60489153
You're missing the point. The only thing copied in the move operation is the universal reference of str1 (pretty much the pointer to its underlying contents) to str2. The contents themselves are not copied.
>>
>>60489312
I know, but there's always exactly that one jerk in a codebase who overloads things he doesn't know of.
It's not as full of jerks as a MATLAB codebase, though.
>>
>>60489335

Right. I'm not sure where rvalue references fit into this.
>>
>>60489360

Just declare your shit with fully qualified namespaces in the header.
Use using declarations to make your code readable in the .cpp
This isn't a problem at all.
>>
>>60489282
If you're writing scripts, you're golfing, working on a competitive programming problem or are just writing some test code for yourself it's not bad style anon. In fact it would be stupid not to use it.

Even when using it when implementing functions for your library it's not bad style. C++ is an OOP language, meaning you as a user of a class should not be concerned with the implementation of it.

Where the 'using std is bad style' comes from is when you use it in headers. If you use it in headers, everyone that includes your header will have a 'using std' statement in their code, which is obviously not what you want.

But really, using is a damn useful tool to shorten your code (especially when dealing with shit like std::chrono::, which gets tiring really soon).
>>
>>60489331
Change 'auto w' to 'auto const &w', that should speed things up a lot.

Also, I never claimed that my solution was fast. It was designed to be concise.
>>
>>60489409
PYTHION IS MORE CONCISE AND MORE FASTER TOO
HISSSSS
SSSSSSS
SSSSSSS
SSSSSSS
>>
>>60483918
C plus OOP concept put together with ducktape.

Not a single decent built system

Shit overly complicated syntax

Only redeemable quality is that it's fast.
>>
>>60489439

OOP is the shittiest reason to use C++

Templates + STL is the real winner.
>>
>>60489015
I'm trying to learn C++, please can somebody walk me through this code?

>ifstream in(argv[1], ios::in);
what's the purpose of std::ios:in here? what happens to the varialbe in later?

>string line;
>while (getline(cin, line))
I'm assuming getline reads a line from std::cin and sets it to the line variable? but how does that happen if we didn't pass the string line as a reference?
>>
>>60489390
I don't dispute this, I'm using it for fast scripts (or my own shit) as well, it just has the little perks that you and I mentioned. That's why it's frowned upon by many. People in transistion fronm hobbyist programming to professional coding should see the danger in this, though. And not everyone will.
>>
>>60489409
new time:

$ time ./a.out <in >/dev/null

real 0m2.537s
user 0m2.456s
sys 0m0.072s
>>
File: 0.jpg (137KB, 1280x956px) Image search: [Google]
0.jpg
137KB, 1280x956px
>>60489435
Nothing wrong with Python.
>>
>>60489459
The templates make things so fucking awesome.
>>
>>60489461
std::ios::in is a flag

line is actually passed as a reference
>>
>>60489223
>for line in file returns each line of the file as a string
>uses .split() which is a string method
you actually can, but it requires a certain minimum intelligence
>>
File: donald-trump-shrug-1024x551.jpg (101KB, 1024x551px) Image search: [Google]
donald-trump-shrug-1024x551.jpg
101KB, 1024x551px
>>60489476
As I've said, it wasn't designed to be fast. The solution by >>60486047 is much faster.

It's no suprise the Python script is fast because almost everything in there is implemented in C.
>>
>>60489535
So you are suggesting if you wanted numbers only you would use the split function from ... integer.split or what?
Fuck off retard.
>>
>>60489557
PTHYON WINS AGAYIN
>>
File: dman-rain.jpg (36KB, 640x640px) Image search: [Google]
dman-rain.jpg
36KB, 640x640px
>>60489506
>he thinks C++ templates are any good
>>
>>60489584
They indeed are.
>>
>>60483918
>even if you write shit code it is still the fastest
So this is why /g/ code monkeys like C/C++ so much
>>
>>60489560
Fuck are you on about? You post some shit code that doesn't replicate the functionality of the original, and then trigger like a bitch?
>>
>>60486047
Can you tell me what this program does? Looks really too autistic to me
>>
>>60489642
Something different to what >>60484478
does.
>>
>>60489584
>>60489600

> implying C++'s templates are not good
> implying this is better

func int64Sum(list []int64) (uint64) {
var result int64 = 0
for x := 0; x < len(list); x++ {
result += list[x]
}
return uint64(result)
}

func int32Sum(list []int32) (uint64) {
var result int32 = 0
for x := 0; x < len(list); x++ {
result += list[x]
}
return uint64(result)
}

func int16Sum(list []int16) (uint64) {
var result int16 = 0
for x := 0; x < len(list); x++ {
result += list[x]
}
return uint64(result)
}

func int8Sum(list []int8) (uint64) {
var result int8 = 0
for x := 0; x < len(list); x++ {
result += list[x]
}
return uint64(result)
}


Meanwhile:

accumulate(vec.begin(), vec.end());


vec can be any container that supports a iterator that can be incremented, and vec can contain any type that supports the '+' operator. That's right, this includes all numerical types, types from libraries that support it (matrices), strings, your own types, you name it.

When the Ranges TS hits in C++20, this can be written simply as:

accumulate(vec);


Because believe it or not, C++ sets a high standard for itself and continues to improve.

You have a point though. Templates have problems, especially when writing them. Most of these problems will be solved with Concepts. These are constraints you put on types that can be passed to templates. Instead of generating a wall of errors, you'll see which constraints are not satisfied when you try to pass some type to a template.

They are definitely 'any good' though. They are a very powerful feature (actually so powerful that they are Turing complete, for exampe, you can print the first 100 prime numbers by COMPILING a C++ program).
>>
>>60489666
What does >>60484478 do?
>>
>>60489666
>>60489642
>>60489750

#include <iostream>
#include <fstream>
#include <deque>
#include <sstream>

int main (int argc, char **argv)
{
std::string line;

while (std::getline(std::cin, line))
{
std::deque<std::string> l;

std::istringstream linestream(line);
std::string word;
while (linestream >> word)
{
l.emplace_back(word);
}

for (auto it = l.end() - 1; it >= l.begin(); it -= 2)
{
std::cout << *it << " ";
}
std::cout << "\n";
}
}


Now it does the same.
>>
>>60489781
What is it doing? Reading text in a file and printing them?
>>
>>60489750
It prints each line in reverse, but only prints the words with an even index (counted from the end).
>>
>>60489015

New to C++. Would anons help me out a little?

std::ifstream cin(argv[1], std::ios::in); // Creating and input file stream using the path provided from arg1
std::string line;

while (getline(cin, line)) // read line from the file stream into variabe "line"
{
std::istringstream ss(line); //take the line and push it into a input string stream
std::vector<std::string> words( // Vector is a self-resizing array that we're initializing with a stream and an iterator
std::istream_iterator<std::string>{ss}, //
std::istream_iterator<std::string>());
copy_if(words.rbegin(), // No clue what copy_if is defitiion based below
words.rend(),
std::ostream_iterator<std::string>(std::cout, " "),
[i = 0](auto w) // I'm guessing when these iterators start they set i=0, w would be what ever they're handling gets passed in, but we're trashing that.
mutable // What's being made mutable?
{ return i++ % 2 == 0; }); // This is true for every even number

// What is [i=0]? Can there be a space between [i=0] and (auto w)?
std::cout << '\n';
}


// I know generics from C# but unsure wtf this is
template<class _InIt, // _InIt = Input iterator
class _OutIt, // Output iterator
class _Pr> // Predicate
inline // inline is for the compiler to write the assembly inline instead of having a ret/call? maybe?
_OutIt copy_if(_InIt _First, _InIt _Last, _OutIt _Dest,
_Pr _Pred)
{ // copy each satisfying _Pred
_DEBUG_RANGE_PTR(_First, _Last, _Pred);
return (_Copy_if(_Unchecked(_First), _Unchecked(_Last),
_Dest, _Pred, _Is_checked(_Dest)));
}
>>
>>60489733
>adopting even more features D has had for years
someone wrote a compile time raytracer in D a decade ago
>>
>>60489801
So you want a function such that
fn(abcdef) prints fdb?
>>
>>60489809
I wrote it, happy to help. You're also always welcome over at ##c++ on freenode.

It's mostly showing off some STL functions, as was already pointed out, it's not the most efficient solution.
std::copy copies things from an iterator range, to an iterator range.

std::copy_if copies only if a certain condition is satisfied, it takes a function object that takes an element of the input iterator range (you're right, we're not using that in this case).

A function object is something that () can be used on. Can be a function pointer, a class with an overloaded () operator or, in this case, a lambda.

Inside the square brackets is the capture list, in this case we're capturing a new variable i and nothing from the outer scope. The lambda is made mutable so we can modify the i. Lambda's are very flexible with notation. You can sprinkle spaces around.
>>
>>60489733
>implying someone didn't write all the template code to begin with
>implying when working with your own types you won't have to write all those functions anyway, just with Template Syntax (TM)

>for exampe, you can print the first 100 prime numbers by COMPILING a C++ program).
>this is a good thing
>>
>>60489916

Never put off till runtime what you can do at compile time.
>>
>>60489846
Yeah it's not an easy language to learn, if only due to it's size. People decing to learn C++ are in for a ride. I found it to be worth it though. Lots of job opportunities, and I've come to love the language and it's power, how creative you can be with it and even some of it's quircks (i.e. the most vexing parse).

>someone wrote a compile time raytracer in D a decade ago

Pretty epic. Now write a HTTP server. :P
>>
>>60489939
touche, but I doubt the code written to do that is understandable or maintainable.
>>
>>60483934
Your point ?
>>
>>60489809
please don't read the implementation of template functions if you're just starting out :P

http://en.cppreference.com/w/cpp/algorithm/copy
>>
>>60489809
but as you can see the reference implementation at cppreference is pretty readable
>>
>>60483918
No. C++ is not fast by default, it is fast if you optimize it, and do things like allocate small objects of known size into a pool, etc.

If you don't know what you are doing, Java or C# will tend to be as fast or faster. They just won't have as much opportunity for optimizations.
>>
>>60489872
pls respond
>>
>>60490052

it'll be faster as soon as you start managing object lifetimes instead of relying on the GC
>>
>>60484888
And this is why C++ leads to dependency hell.
>>
>>60490017
>>60489887
>>60490025

Thank you anons.

Could you explain what constexpr does?
>>
>>60490277

force compile-time evaluation
>>
>>60483918
It'll blow up in your face if you write bad code. Other languages compete by being easier, so you save money with productivity.
>>
>>60489887
How do I get chat rights?
>>
>>60489331
Can someone explain that image to me?
>>
File: Screenshot_2017-05-20_02-00-47.png (12KB, 390x152px) Image search: [Google]
Screenshot_2017-05-20_02-00-47.png
12KB, 390x152px
>>60490277
constexpr when used with a variable definition is an indicator that the value is known at compile time. It can then be used in contexts that require compile-time constants (for example, when specifying the size of a static array);

size_t constexpr n = 10;
int arr[n];


It can also be used with function return values. Then, if it gets passed constexpr parameters, the return value with be constexpr.

costexpr add(size_t a, size_t b) {
return a + b;
}

size_t constexpr a = 5;
size_t constexpr b = 6;
int arr[add(5, 6);


This is useful not only because you can make complex calculations (more complex than adding) and use the result of that compilation at compile time (also for, for example, template parameters).

std::array<int, add(4, 5)> arr;
>>
>>60490543
I forgot the size_t in the add function definition and the closing ] in the arr.

>>60490349
IRC help is off-topic here, check /sqg/
>>
File: 1492412873819.png (216KB, 380x364px) Image search: [Google]
1492412873819.png
216KB, 380x364px
>>60489872
>>60489801
Really? that's what you needed?
import std.stdio;

void main()
{
string read = readln;
bool write = true;
foreach(index, character; read.dup.reverse)
{
if (write)
{
character.write;
}
write = !write;
}
writeln;
main();
}
>>
>>60490611

I have no idea what language that is, but you should print words not characters.
>>
>>60490866
Isn't this what you wanted?
>>
>>60490920
Oh there's a bug
>>
>>60490611
what language is that?
>>
>>60490951
D
>>
>>60490920

IN:

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Proin mauris sapien, tristique ac molestie at, bibendum non felis.
Praesent lobortis ex nec eros pulvinar volutpat. Cras diam nulla, sollicitudin ac nulla at, tristique vehicula ipsum.
Sed vitae nulla lacinia, rhoncus massa eu, rhoncus libero. Quisque diam justo, ultricies ac pellentesque ac, convallis ut neque.
Cras luctus elementum augue, non mollis massa faucibus nec. Suspendisse vitae dolor porttitor nisi placerat congue sed lacinia mi.
Curabitur sit amet pharetra tortor, eget maximus urna. Fusce orci urna, auctor ut nisl sit amet, vehicula condimentum urna.
Integer molestie elit a tempus blandit. Sed sed lorem nec quam hendrerit fringilla. Suspendisse vulputate sed sem quis ultrices.


OUT:
elit. consectetur sit ipsum 
felis. bibendum molestie tristique mauris
ipsum. tristique nulla sollicitudin diam volutpat. eros ex Praesent
neque. convallis pellentesque ultricies diam libero. eu, rhoncus nulla Sed
mi. sed placerat porttitor vitae nec. massa non elementum Cras
urna. vehicula sit ut urna, Fusce maximus tortor, amet Curabitur
ultrices. sem vulputate fringilla. quam lorem Sed tempus elit Integer
>>
>>60491067
Oh that. One sec
>>
File: RMS.png (146KB, 540x370px) Image search: [Google]
RMS.png
146KB, 540x370px
>>60484478
>>60489331
yes 111111 22222222 333333333 44444444 555555555 666666 7777777 888888888 9999999999 0000000 | head -n 1000000 > yes.in

time awk 'BEGIN { ORS=" ";} { for (i=NF; i>0; i -= 2) print($i); printf("\n"); }' < yes.in > yes.awk.out

real 0m3.824s
user 0m3.425s
sys 0m0.212s

time ./py.py yes.in > yes.py.out

real 0m8.985s
user 0m8.439s
sys 0m0.278s

BTFO
T
F
O

UNIX wins once again.
>>
>>Why did you use bubblesort?
>>Oh don't worry i wrote it in c++ so it will be fast
>>
Node.js
>>
>>60491067
When does your program stops reading from the input? What's the END switch?

Here is one that reads until RETURN is pressed in the keyboard
import std.stdio;

void main(string[] args)
{
foreach (index, arg; args[1 .. $].reverse)
writef("%s", index%2 ? " " : arg);
}


So the compiled result is
[user0@primary test-d]$ ./main  Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
elit. consectetur sit ipsum
[user0@primary test-d]$ ./main Proin mauris sapien, tristique ac molestie at, bibendum non felis.
felis. bibendum molestie tristique mauris
[user0@primary test-d]$
>>
>>60488019
C++ move semantics are shit-tier
Rust BTFO's C++
>>
>>60489015
I develop mostly in Python for work, but I've got to give you kudos. This is much nicer C++ code than I'm used to seeing.
>>
File: index.jpg (8KB, 273x185px) Image search: [Google]
index.jpg
8KB, 273x185px
>>60491315
using command line arguments as input
>>
>>60492250
Welcome to systems programming
>>
>>60488166
>>tfw too dumb to understand move semantics

>>60488271
>It's just taking the meat of a structure and leaving a skeleton.

It's more like Chinese organ harvesting.

> oh hey there mister political dissident, it looks like you don't need those lungs and spleen any more, I'll just be taking those ...

the basic notion is that the compiler can tell from context when a variable isn't going to be used any more (or told explicitly through
std::move()
etc. which is effectively just a cast), and functions can be written to accept these as parameters knowing that they can steal parts from objects living on borrowed time.

this only really is worth anything when a resource to be harvested lives outside the stack, such an "owning" pointer into a heap allocated object/collection or a handle to an operating system resource.
>>
>>60491213
kek
>>
So, I'm a beginner with C++, I have some background in C and Python (I'm not trying to graduate to C++, I've started over from the beginning)

I've learned a lot of the basic syntax, but I'm wondering if there are any free online sources for understanding principles, good practices, and thinking with C++, all I can find are syntax tutorials, people telling me to buy textbooks ( I want to, but can't right now), and talks on youtube talking about how important these things are, but nothing that is an actual rundown on these lessons.

Any help?

Otherwise is there are source for reading text book pdfs online (assuming I buy one, I can't use apps or pdf readers outside of browsers).
>>
>>60494890
Honestly anyone starting with C++ should just read stroustrups book http://stroustrup.com/Programming/ and do the exercises at the end of each chapter. Even an old timer C++ programmer have much to gain from reading that book. Especially due to the C++11/14 update. It teaches you how the std is built up, best practises and how to work with the common features.
>>
>>60495003

Not having that book is the exact problem I'm trying to circumvent.

I can't really afford it right now, so I was looking for some alternatives that can supplement me in the mean time.
>>
>>60495016
Online resources can only take you so far. I don't think I ever seen a good online learn C++ resource that doesn't teach bad practises. Read a book and use stackoverflow for issues that can't be googled.

The best C++ progression is here https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list. Anything Scott Meyers is a good bet for more advanced levels.

And I'm not sure where you live but my local library have the latest Programming edition on the shelf. Check your nearest libraries and university libraries.
>>
>>60495084

Ok, I will, but I'm like 18 hours away from getting a chance to do that and have about 5 hours in my lap right now.

Are there any atleast non-damaging books that I can read through an online pdf for free that you know of? Even if they aren't great?

Or any lectures or talks even if they aren't guides.
>>
>comparing python to c++
Why

They're used for wildly different things.
You should learn both.
>>
>>60495141

I wasn't comparing them, I always intended to learn C++ but was told to dip my toes in other languages first.

I have nothing against Python.
>>
>>60495111
I'd just advise you to buy or borrow ("borrow" from a friendly internet resource) the e-book or something. Not sure what circumstances you are under that prevents you from doing that.
>>
>>60483918
Its easier than java
>>
>>60495211
The worst thing about Qt is that they somehow thought Java style iterators were a good thing.
>>
Why do people advise that you learn C++ rather than taking a C first approach, if you want to eventually wind up using C++?

Provided you're happy to spend a lot of time learning, and you're able to think objectively enough to not equate C to C++, is there any downside?

Does the verdict change if you think you're going to largely be writing for C-with-classes-style codebases anyway?
>>
>>60495289
C is not object based. C++ is a superset of C but that doesn't mean you actually use any C features at all in modern C++. The syntax is familiar but I honestly see no reason to learn C unless you are going to contribute to the linux kernel.
>>
>>60495289
People who learn C first are forever spoiled and continue writing shitty C code even in another languages, refusing to adopt modern features because they are "slooow".
>>
>>60483918
Yet it can't handle polymorphism unless you tell it to.

Hurr durr virtual function durr
>>
>>60494890
Of course there are online resources however if you are too retarded to find those on your own you will not be able to comprehend them anyways.
>>
>>60495706
Because virtual functions introduce overhead(vtable). In sepples classes without virtual functions are as efficient as structs.
>>
>>60495369
I agree with you, except for the "no reason to learn C" part though. It is quite useful to learn C and understand how it synthesizes to assembly, and it will increase your understanding of C++ and other programming languages.

>>60495289
>Why do people advise that you learn C++ rather than taking a C first approach, if you want to eventually wind up using C++?
I programmed in C 8 years before I learned C++.

>Provided you're happy to spend a lot of time learning, and you're able to think objectively enough to not equate C to C++, is there any downside?
I haven't experienced any clear downsides, so I would say go for it. It is important that you differentiate between them, as they really are different languages.

>Does the verdict change if you think you're going to largely be writing for C-with-classes-style codebases anyway?
Don't do this.
>>
>>60495706

why would you introduce overhead unless you have to?

Virtual functions are dangerous af anyway, I prefer to make most classes final.
>>
>>60495743
Except, you know, implicit ctors and dtors
>>
>>60495795
This.
RAII is what makes C++ truly great
>>
>>60495795

if you're not using polymorphism or member variables that must be initialized, then the implicit ctors are trivial and elided.
>>
>>60495830
In C I can pass around uninitialised structs, in sepples I can't.

If a struct member is another struct, then you really have the ball rolling.
>>
>>60495779
>It is quite useful to learn C and understand how it synthesizes to assembly,
I've programmed C and C++ for a living the past 25 years. I don't see how this statement is even relevant. If you want to understand that read compiler theory.
>it will increase your understanding of C++ and other programming languages.
I don't really see how an imperative language can increase the understanding of C++ except that many languages use a C like syntax.
>>
ITT: NEETs arguing over shit that don't matter
>>
>>60495843
fucking stupid point unless you are doing ABI then yes I agree
>>
>>60495866
>If you want to understand that read compiler theory.
You don't want to read compiler theory to understand calling conventions and ABIs, anon. That's like recommending taking a master's degree in electrical engineering in order to learn how to solder.

>I don't really see how an imperative language can increase the understanding of C++ except that many languages use a C like syntax.
C++ is also an imperative language, anon. Object-orientation is an imperative paradigm.
>>
>>60495886
>fucking stupid point
Partial initialisation is an often used optimisation technique, anon. You find it all over the Linux kernel, for example.
>>
>>60495843

You're plain wrong about that. POD structs work exactly like structs do in C.
Like most C++ haters, you don't know the language you're criticising.
>>
>>60495929
>POD
Follow the chain of posts, anon. The original poster specifically claimed that classes with no virtual methods were as efficient as PODs. (see >>60495743)
>>
>>60495889
>That's like recommending taking a master's degree in electrical engineering in order to learn how to solder.
If you enjoy being a solder robot then yes you don't need to understand anything.

>C++ is also an imperative language, anon. Object-orientation is an imperative paradigm.
Ah yes I'm retarded. I'm thinking of something else but can't find the English translation.
>>
>>60495964

You're thinking of procedural.
>>
>>60495954
The only difference between structs and classes in C++ is that classes have private access modifier by default instead of public.
>>
>>60495964
>If you enjoy being a solder robot then yes you don't need to understand anything.
First of all, soldering is a practical skill, much like running your program through a disassembler.

Secondly, an engineering degree doesn't even teach you how to solder. This is the important analogy to compiler theory, because it may teach you how to create ASTs and optimisation theory and how to make a generic compiler and so on, but it doesn't really teach you x86 instruction specifics. For that, you would have to actually look at a compiler, which is also overkill.

>Ah yes I'm retarded.
I don't think you are.

>I'm thinking of something else but can't find the English translation.
Probably "procedural" which gets used a lot on /g/ (but isn't really an agreed upon paradigm in programming theory).

Anyway, C is easier to compile and look at through a disassembler, because of simpler naming conventions and lack of virtual functions and compiler generated functions.
>>
>>60495988
That has fucking nothing to do with the discussion.

We are talking about how C++ generates implicit constructors and destructors and how this may be an overhead compared to simply not initialising your members.
>>
>>60495954

That's true, but that's not the point you're making and the point I was responding to. >>60495843

You can pass around uninitialised/partially initialised structs and they don't even need to be POD.
>>
>>60496027
>That's true, but that's not the point you're making and the point I was responding to. >>60495843
I am both posters, I think I know what the point I am making is.....

>You can pass around uninitialised/partially initialised structs and they don't even need to be POD
But then you'd have to explicitly define ctors and dtors, which was my point. Relying default ctors and dtors can be bad for you in certain cases.
>>
>>60496041

>But then you'd have to explicitly define ctors and dtors, which was my point.
If you don't define ctors then you'll be given default ones. And if you don't have any virtuals or members whose types mandate initialization, those default ctors will be trivial and won't initialise anything.

The only time your default ctors initialise shit is when the types of those members require them to. If you're aware of what you're actually putting in your struct then the default ctor is never an issue.
>>
>>60496085
>If you're aware of what you're actually putting in your struct then the default ctor is never an issue.
Well, I guess we agree then. You need to take care what you put inside your struct, whether it is the members themselves or the ctors.
>>
>>60496004
>it doesn't really teach you x86 instruction specifics
I'm arguing that it's more beneficial to understand how everything actually works. I feel the stuff you talk about come for free with that knowledge. But then I work with different CPU architectures and operating systems.

>Anyway, C is easier to compile and look at through a disassembler, because of simpler naming conventions and lack of virtual functions and compiler generated functions.
Yes but how does that help with C++ or a language using a jit or aot?

I just may take a lot of knowledge for granted that I've learned over the years but in 2017 I don't really see much use for C for most people. It's far more important to understand platform specific handling of libraries like dlls on windows and what the pitfalls are. Using a dll with another version of crt than your code or that was compiled with another set of stl headers can be a nightmare to sort out with C++.
>>
>>60489584
>implying they aren't

Go ahead, make a case for it
>>
>>60494890
http://www.icce.rug.nl/documents/cplusplus/

pdf on github
>>
>>60491067
>>60484478
actually working D version:
import std.stdio : writeln, File;
import std.range : split, retro;
import std.algorithm.iteration : map, joiner, each;

void main(string[] args)
{ args[1].File
.byLine
.map!split
.map!retro
.map!(a => joiner(a, " "))
.each!writeln;
}


>>60490611
>using loops and conditionals
not needed
>>
>>60496941
actually fucked up
this works however:
import std.stdio : writeln, File;
import std.range : split, retro, stride;
import std.algorithm.iteration : map, joiner, each;

void main(string[] args)
{ args[1].File
.byLine
.map!split
.map!retro
.map!(a => stride(a, 2))
.map!(a => joiner(a, " "))
.each!writeln;
}
>>
>>60483918
confirmed for shit programmer
>>
>>60496973

what's ! all about? Is this lambda syntax?
>>
>>60496980
! is for templates
(a => stride(a, 2)) is a lambda
>>
>>60496991

So
map!split
instantiates a function template of map with split as the parameter?
That's pretty rad actually.
>>
>>60496978
t. LARPer
>>
>>60496973
>Importing 3 fucking libraries
Disgusting
>>
>>60496101
>Yes but how does that help with C++
C++ synthesizes to C quite trivially, anon. You know this very well if you've been programming C and C++ for 25 years.
>>
>>60496101
>It's far more important to understand platform specific handling of libraries like dlls on windows and what the pitfalls are. Using a dll with another version of crt than your code or that was compiled with another set of stl headers can be a nightmare to sort out with C++.
Also, in the case of dynamic linking, I learned how this worked by looking at disassembled dynamic linking stubs and using object tools to inspect the binary executable.
>>
>>60489331
>nearly
Use 10 000 000 entries. I'll wait.
>>
>>60489129
>>60489781
>complains that the code is complete and utter shit that is lightyears away from doing what its supposed to
>changes one thing
>NOW ITS WORKING
if the code really was so bad you would have had to change more than int->string
fucking larpers
>>
>>60484478
this could probably be way nicer

import System.Environment

main :: IO ()
main = do
file <- readFile =<< (head <$> getArgs)
putStrLn . unlines . map unwords $ (map (second . reverse . words) . lines) file
where second xs = map fst $ filter snd (zip xs $ cycle [True, False])
>>
>>60497197
Why would anyone use C only features in C++?
>>
Why should I learn C++ if I know C?
And before you instantly say OOP, why should I switch to OOP when Structured programming works fine?
>>
>>60502104

templates and stl
>>
>>60502104
Lambdas, templates, operator overloading, uniform initialization syntax, move semantics, type deduction, user defined literals, ability to compute stuff at compile time, etc. OOP is shit.
>>
>>60502104
Since you are a NEET you don't need to learn anything.
If you have a job, learn what is needed for that.
>>
>>60502364

>uniform initialization syntax
This only occurs as a consequence of OOP data encapsulation, POD structs already had this functionality.
>ability to compute stuff at compile time
this is the same thing as templates
>move semantics
2complicated4me
>>
>>60502395
>uniform initialization syntax
But it also allows you to have stuff like initializer lists.
>this is the same thing as templates
I was talking about constexpr.
>>
File: 1439607763680.png (7KB, 377x326px) Image search: [Google]
1439607763680.png
7KB, 377x326px
>>60483918
It's pretty nice once you get the hang of it, in my opinion. I had really low standards coming from lisp but it hasn't been too bad actually. It's kind of tedious doing things in an idiomatic C++ style, but given that compilers today can leverage tail call optimization for recursion and STL containers it's really not a big problem. I sometimes get tripped up on expressions vs. statements and manual returns, but that would happen in any language. People make it out to be a lot worse than what I've experienced, but I heard that C++ now is a totally different beast than C++ 98 and the way it used to be.
>>
>>60502926
In the beginning there were no "official" string classes in C++. I've worked at places that rolled their own string classes back in the 90s due to not trusting third party libs.
>>
>>60503122

legacy is the biggest issue with C++

Any codebases that haven't been modernised with C++11 are hell. Honestly C++ before 11 deserves its reputation.
>>
>>60490391
Programming languages personified.
>>
>cost for a server per month: $10
>cost of programmer per hour: $30

That's how other languages compete
>>
>>60502926
>compilers today can leverage
compilers today can use
>>
>>60505529
thanks
>>
>>60488148
>For GUI and other frontend stuff I just use Qt if I want to contaminate my code.
What do you mean by that? I was looking to learn Qt.
>>
>>60505985
Qt is like GPL. It contaminates the code because you have to use their custom signal and slot mechanism (event mechanism) that requires an additional preprocessing tool (moc). This requires a QApplication that blocks your main thread to pump the signal message queue.

You also have to use their types (QString etc). It's heavily inspired by Java and java type iterators. When you think you are copying a QObject you are actually passing a pointer. It uses copy on write and other techniques that promotes bad coding practises.

I'd recommend keeping Qt in the very frontend only and in very separated utility classes that parses json or xml and similar. Preferably I'd just go with another third party lib.

Still it's the best multiplatform GUI framework for C++ in my opinion. Also there are some questions around the way they are going when it comes to licensing. I'm quite certain they are going full blown GPLv3 within a few years to increase commercial license sales.
>>
>>60495713
There is a lot of material on C++, most of them badly written or plainly wrong or inducing error and teaching bad practices.
>>
>>60506237
Oh an everything have to run in the same thread or be started with Qt's own thread library. Otherwise the signal and slot mechanism will fuck up
>>
>>60484423
File access, string manipulation, datastructures. Why the fuck aren't these things fleshed out but all kind of useless crap did get put in?
>>
>>60506237
>>60506338
Ok, that's seriously unstimulating.
>>
>>60506558
Because there's Boost to cover most of them and they try to focus on things that are not system dependent? I mean, Boost is the official extra-official C++ extra suit of libraries.
>>
>>60506704
Boost represents everything that is wrong with C++.
>>
>>60506631
Indeed but it's quite easy to work and provides similar functionality as .Net framework. I just advice caution when using it so you don't go full retard and use Qt classes everywhere. Once you go that deep it will be more or less impossible to de-Qtfy it without make a complete rewrite.
>>
>>60506736
How so? I am curious because a beginner and I see that many od the new features of the newer versions of C++ come from Boost.
>>
>>60506889
I see, as I only have experience with Swing and Tk I man take this later, focus on getting better on the language. Thanks for the review.
>>
>>60483918
Great language, but you can't check if a number is prime in 1 line.
>>
>>60506895
It's an old meme. Boost is fine to use now, and you can pick and choose which parts you want to use without any trouble.
>>
>>60506962
isPrime(num);
>>
>>60507667
Incredible.
>>
>>60506558
I don't see why it matters, you write a library for string methods in like an hour and you never have to do it again.
>>
>>60499219
And people believe Haskall is the future.
Thread posts: 198
Thread images: 12


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.