函数在C++中返回迭代器

suf*_*que 11 c++ iterator

以下是返回迭代器的Java方法

vector<string> types;

// some code here

Iterator Union::types() 
{
    return types.iterator();
}
Run Code Online (Sandbox Code Playgroud)

我想将此代码翻译为C++.如何从此方法返回vector的迭代器?

hmj*_*mjd 15

这将返回一个迭代器到types:

std::vector<string>::iterator Union::types() 
{
    return types.begin();
}
Run Code Online (Sandbox Code Playgroud)

但是,调用者也需要知道end()向量types.Java Iterator有一个方法hasNext():这在C++中不存在.

您可以更改Union::types()为返回范围:

std::pair<std::vector<std::string>::iterator, 
          std::vector<std::string>::iterator> Union::types()
{
    return std::make_pair(types.begin(), types.end());
}

std::pair<std::vector<std::string>::iterator, 
          std::vector<std::string>::iterator> p =  Union::types();

for (; p.first != p.second; p.first++)
{
}
Run Code Online (Sandbox Code Playgroud)


Sea*_*ean 9

你想要一个beginend方法:

std::vector<string>::iterator Union::begin()
{
  return types.begin();
}

std::vector<string>::iterator Union::end()
{
  return types.end();
}
Run Code Online (Sandbox Code Playgroud)

为了完整起见,您可能还想拥有const版本

std::vector<string>::const_iterator Union::begin()const
{
  return types.begin();
}

std::vector<string>::const_iterator Union::end()const
{
  return types.end();
}
Run Code Online (Sandbox Code Playgroud)