explain the code please

Nov 24, 2020 at 6:47pm
so i have a code here, could you please explain what these brackets do "{}" (not the ones after int main() but the ones as in sp{ test.find(' ') } etc )

also, what is "npos"?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 #include <string>
#include <iostream>
using namespace std;
int main()
{
	const string test{ "basketball is a popular sport" };
	string test1{ test };

	const auto sp{ test.find(' ') };

	if (sp != string::npos)
		test1.append(" ").append(test, 0, sp).erase(0, sp + 1);

	cout << test << '\n';
	cout << test1 << '\n';
}
Nov 24, 2020 at 6:56pm
List initialisation. It's just a way to set the initial value of something.


const string test{ "basketball is a popular sport" };
This string's initial value is "basketball is a popular sport".

You'd get the same outcome here with
const string test = "basketball is a popular sport";


const auto sp{ test.find(' ') };
This creates an object of type <whatever string::find() returns>, initial value whatever comes back from the function call test.find(' ')

https://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives


string::npos is the special value returned by string::find if it didn't find what you're looking for.
https://www.cplusplus.com/reference/string/string/find/ (look at "Return Value" section).
Last edited on Nov 24, 2020 at 6:57pm
Nov 24, 2020 at 6:57pm
In that content the braces are being used for Uniform Initialization, so that line is initializing the variable sp to the return value of the test.find(' ') function.

Nov 25, 2020 at 7:32am
thank you so much, this helped a lot!! :)
Topic archived. No new replies allowed.