Mar*_*rty 3 c++ iterator vector
如何保存min_element的值?它说它是一个前向迭代器,但我似乎无法弄清楚如何保存(分配给变量)它.我希望能够通过向量中的位置访问它.我能找到的只是使用实际元素的例子(使用*min_element()).我试过了
iterator< forward_iterator_tag, vector<string> > min_word_iterator = min_element(first_words_in_subvecs.begin(), first_words_in_subvecs.end());
但那没用.我要用不同的元素替换该索引处的元素.
用这个:
std::vector<T>::iterator minIt = std::min_element(v.begin(),v.end());
//where T is the type of elements in vector v.
T minElement = *minIt; //or T & minElement = *minIt; to avoid copy!
Run Code Online (Sandbox Code Playgroud)
在C++ 11中(如果您的编译器支持auto关键字),那么:
auto minIt = std::min_element(v.begin(), v.end());
//type of minIt will be inferred by the compiler itself
T minElement = *minIt; //or auto minElement = *minIt;
//or auto & minElement = *minIt; to avoid copy
Run Code Online (Sandbox Code Playgroud)