string box;
string is a type and box is a variable name.
Which one is assignment?
int a=3;
vs
a=5;
C++ compiler cannot guarantee complete type safety.
double x;
double y=x;//?
double z=2.0+x;//?
double x=2.7;
int y=x;
int z=5/2;
double w=2.5/2;
y is 2. z is 2. (round-down.) w is 1.25.
int a=1000;
char b=a;
b depends on machine.
double x {2.7};
int y {x}; //ERROR!
int a{1000};
int y {x}; //ERROR!
char b1 {1000};// ERROR!
Expression computes a value.
10
, 'a'
, 3.14
or "Hi"length=9
Statements Statement is the smallest standalone element that expresses some action.
a=b;
++b;
a=b++b; //Syntax error:missing semicolon
int a=2;
cout<<a<<endl;
1+2; // Ok! Nothing.
if (x==5);//empty statement!
{
y=3;
}
In general,
if (expression) statement else statement
switch (int, char or enum type){
case (constant expression):
statement
...
break;// important!
...
default:
...
break;
}
constexpr double pi=3.141592; // Compile time
int i=2;
const j=i; // running time
constexpr int max=100;
void use(int n){
constexpr int c1=max+7;//OK!
const int c2=n+7; //OK!
constexpr int c3=n+7///Error!
c2=3;// Error
}
Vector is a sequence of elements that you can access by an index(iterator). Yes. It is a better array. We actually say it as a container. Vector also knows its
.
#include <vector>
#include <string>
vector<int> vi(6); // vector of 6 ints initialized to 0
vector<string> vs(4); // vector of 4 strings initialized to ""
vector<double> v; //empty vector
vector<int> v={1,2,3,4,5,6};// vector of 6 ints
vector<string> people={"Jobs","Gates","Larry"}
vector<int> {1,2,3}//{} initialization
vector<int> v={1,2,3,4};
for(int i=0;i<v.size();i++) // Range is [0,v.size())
cout<<v[i]<<endl;
or we can use Range-based for loop (c++11).
for(int x: v) // for each x in v
cout<<x<<endl;
or
for(auto x: v) // auto keyword will find a correct type.(c++11)
cout<<x<<endl;
You can increase the size of a vector by using push_back
member function. push_back
ad adds an element to the end.
vector<double> v; //empty
v.push_back(2.7);//Add 2.7
v.push_back(5.6);//Add 5.6
```c++
You can also delete the last element by `pop_back` member function.
```c++
v.pop_back();//Remove the last one, 5.6.
vector has many extra member functions.
CHECK 4. GET N INPUTS (ASSUME INTEGERS) AND STORE THEM INTO AN VECTOR. CALCULATE THE AVERAGE.
int sum(const vector<int>& v){
//your code
}
int main(){
//your code
}
TYPE INTEGERS AND STOP UNTIL TYPE A NON-INTEGER like 'a'. STORE THEM INTO AN VECTOR. CALCULATE THE AVERAGE.
vector<int> v;
for(int t=0;cin>>t;){
v.push_back(t);
}
If you type something which is not integer, it will stop since cin>>t
will be converted to false. Otherwise it will be converted to true.