Reputation: 13
void test()
{
vector <string> s={"hello world"};
for(vector<string>::iterator it=s.begin();it!=s.end()&&!it->empty();it++)
{
for(auto it2=it->begin();it2!=it->end();it2++)//I don't konw type of it2
{
*it2=toupper(*it2);
}
cout<<*it<<endl;
}
}
In the first loop I can sure that iterator of type is vector<string>::iterator
. I wonder what is type of the it2
(I have already tried use vector<string>::const
). And how can I get the more detail about which type did auto
equal.
Upvotes: 1
Views: 132
Reputation: 303337
it
is an iterator into a vector<string>
. Which means that it
"points to" a string
. So when you write it->begin()
and it->end()
, you're iterating over the string
, which would make it2
have type std::string::iterator
. As smartly noted in the comments by Yakk and Mr. Wakely, this type does not matter. It is simply the type of something that "points to" a char
with which we can iterator over our string
. This is one of the main selling points of auto
- if the name of the type doesn't matter, don't clutter your code with it.
Note that since you never actually need iterators in your code, you could simply avoid them with a range-based for loop:
for (auto& str : s) {
for (auto& chr: str) {
chr = toupper(chr);
}
}
Alternatively, if you ever need to know the exact type of something, I'd recommend the following hack. Make a class template that takes a type but is never defined:
template <typename > struct TD; // for Type Description
And then just stick it in somewhere:
for (auto it2 = ... ) {
TD<decltype(it2)> t;
// ...
}
which would give the following error with gcc 5.2:
main.cpp:16:34: error: aggregate 'TD<__gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> > > t' has incomplete type and cannot be defined
TD<decltype(it2)> t;
^
Notice that the compile error has the complete type of it2
in it.
Upvotes: 5