📅  最后修改于: 2020-09-04 06:54:38             🧑  作者: Mango
在本文中,我们将讨论在C++中集合的不同遍历方法。
我们先创建一个字符串构成的集合。
// Set of strings
std::set setOfStr = {"jjj", "khj", "bca", "aaa","ddd" };
std::set::iterator it = setOfStr.begin();
// Iterate till the end of set
while (it != setOfStr.end())
{
// Print the element
std::cout << (*it) << " , ";
//Increment the iterator
it++;
}
// Creating a reverse iterator pointing to end of set i.e. rbegin
std::set::reverse_iterator revIt = setOfStr.rbegin();
// Iterate till the start of set i.e. rend
while (revIt != setOfStr.rend())
{
// Print the element
std::cout << (*revIt) << " , ";
//Increment the iterator
revIt++;
}
// Iterate over all elements of set
// using range based for loop
for (auto elem : setOfStr)
{
std::cout << elem << " , ";
}
// Iterate over all elements using for_each
// and lambda function
std::for_each(setOfStr.begin(), setOfStr.end(), [](const std::string & str)
{
std::cout<
#include
#include
#include
#include
int main()
{
// Set of strings
std::set setOfStr =
{ "jjj", "khj", "bca", "aaa", "ddd" };
std::cout << "*** Iterating Set in Forward Direction using Iterators ***"
<< std::endl;
// Creating a iterator pointing to start of set
std::set::iterator it = setOfStr.begin();
// Iterate till the end of set
while (it != setOfStr.end())
{
// Print the element
std::cout << (*it) << " , ";
//Increment the iterator
it++;
}
std::cout << std::endl;
std::cout << "*** Iterating Set in Reverse Direction using Iterators ***"
<< std::endl;
// Creating a reverse iterator pointing to end of set i.e. rbegin
std::set::reverse_iterator revIt = setOfStr.rbegin();
// Iterate till the start of set i.e. rend
while (revIt != setOfStr.rend())
{
// Print the element
std::cout << (*revIt) << " , ";
//Increment the iterator
revIt++;
}
std::cout << std::endl;
std::cout << "*** Iterating Set using range based for loop ***"
<< std::endl;
// Iterate over all elements of set
// using range based for loop
for (auto elem : setOfStr)
{
std::cout << elem << " , ";
}
std::cout << std::endl;
std::cout << "*** Iterating Set using for_each algo & Lambda function ***"
<< std::endl;
// Iterate over all elements using for_each
// and lambda function
std::for_each(setOfStr.begin(), setOfStr.end(), [](const std::string & str)
{
std::cout<
*** Iterating Set in Forward Direction using Iterators ***
aaa , bca , ddd , jjj , khj ,
*** Iterating Set in Reverse Direction using Iterators ***
khj , jjj , ddd , bca , aaa ,
*** Iterating Set using range based for loop ***
aaa , bca , ddd , jjj , khj ,
*** Iterating Set using for_each algo & Lambda function ***
aaa , bca , ddd , jjj , khj ,