3.1
namespace intro {
int function() {
return 1;
}
}
int main(int argc, char**argv) {
intro::function();
}
Note:
Name -> 不要再头文件中使用 using
3.2 Library string type
std::string
initialize:
string str1 = "abc";
string str2("abc");
string s4(10, 'c'); // s4 is cccccccccc
读取:
getline(std::cin, string input); // read until enter
cin; // read until space
Read an unknown number of strings:
string word;
while (cin >> word)
cout << word << endl; // read until the end of file ctrl + D
return 0;
Using getline to Read an Entire Line:
string line;
while(getline(cin, line)) {
cout << line << endl;
}
return 0;
size() returns a string::size_type value;
size_t is an unsigned int
str.size() < -1 --> true! //avoid problems due to conversion between unsigned and int by not using ints in expressions that use size().
Adding Literals and strings !!!
string s1 = "Hello" + ","; // errot: + operator 两侧至少有一个operand为string
string s2 = "Hi!";
string s3 = s2 + "," + "Word\n"; // equals to
// string s3 = (s2 + ",") + "Word\n"; // where () return a string type
*****
For historical reasons, and for compatibility with C, string literals are not standard library strings. It is important to remember that these types differ when you use string literals and library strings.
3.3 Library vector type
std::vector
initialize:
vector<int> vec = {1,2,3};
vector<string> str1{"123", "456"};
vector<int> vec1(10); // ten elements of 0
vector<int> v1(10); // v1 has ten elements with value 0
vector<int> v2{10}; // v2 has one element with value 10
vector<int> v3(10, 1); // v3 has ten elements with value 1
vector<int> v4{10, 1}; // v4 has two elements with values 10 and 1
vector<string> v5{"hi"}; // list initialization: v5 has one element
vector<string> v6("hi"); // error: can't construct a vector from a string
literal
vector<string> v7{10}; // v7 has ten default-initialized elements
vector<string> v8{10, "hi"}; // v8 has ten elements with value "hi"
cout << str1[1] << endl; // 456
cout << str1[1000] << endl; // 不会报错
for (int i = 0; i < str1.size(); i++) {
cout << str1[i] << endl; // subscript operator []
}
add elements:
vec.push_back(4); // vec = {1,2,3,4}
3.4: Iterator
vector<int> itr = {1,2,3};
int size = vec.size();
for (i = 0; i < size; i++) {
cout << vec[i];
}
有一些数据结构无序hashset, hashmap(空间不连续),所以用iterator
vector<int> itr = {1,2,3};
// auto -> vector<int>::Iterator
// vector<int>::const_iterator
for (auto it = vec.begin(); it != vec.end(); ++it) {
cout << *it << endl;
}
// 1 2 3
// | |
// begin end
end represents one element pass the last of element
itr.begin() + 2 == itr[2] // because itr.begin() is
//the first element
it++ means move the pointer
vector<string> str = {"abc", "def"};
for (auto it = str.begin(); it != str.end(); ++it) {
cout << (*it).size() << endl; // it->size()
}