for (const auto &s : strs) {} 和迭代器

vector<string> &strs;
for (const auto &s : strs){
//
}

It's actually a C++11 feature called "range-based for-loops".

近似等价于:

// Let's assume this vector is not empty.
vector<string> strs;

const vector<string>::iterator end_it = strs.end();

for (vector<string>::iterator it = strs.begin(); it != end_it; ++it) {
  const string& s = *it;
  // Some code here...
}

感觉确实精简了许多。

迭代器的几种输出方式:

#include<vector>
#include<string>
#include<iostream>
using namespace std;
int main(){
	vector<string> text;
	string word;
	while (getline(cin, word)){//循环读入字符串至vector<string>中,以trl+z回车结束
		text.push_back(word);
	}
	//下标迭代方式输出
	cout << "下标迭代方式输出" << endl;
	for (vector<string>::size_type ix = 0; ix != text.size(); ++ix)
		cout << text[ix] << endl;

	//迭代器方式输出
	cout << "迭代器方式输出" << endl;
	for (vector<string>::iterator it = text.begin(); it != text.end(); it++){
		cout << *it << endl;
	}
	//int result = uniqueMorseRepresentations(text);

	//精简迭代方式输出
	cout << "精简迭代方式输出" << endl;
	for (const string& words : text){
		cout << words << endl;
	}
	getchar();
	return 1;
}

猜你喜欢

转载自blog.csdn.net/akenseren/article/details/80408208
今日推荐