How can I build a std::vector and then sort them?

前端 未结 7 2062
一向
一向 2021-02-06 22:09

I have a bunch of strings that I need to sort. I think a std::vector would be the easiest way to do this. However, I\'ve never used vectors before and so would like some help.

相关标签:
7条回答
  • 2021-02-06 23:02

    Sorting the string:

    using namespace std; // to avoid using std everywhere 
    std::sort(data.begin(), data.end()); // this will sort the strings
    

    Checking whether vector is sorted:

    if(vec.empty())
        return true; // empty vector is sorted correctly
    for(std::vector< std::string>::iterator i=vec.begin(), j=i+1; j != vec.end(); ++i, ++j)
        if(*i > *j)  return false;
    return true; // sort verified
    

    C++11 Method to check sorted vector: std::is_sorted(vec.begin(),vec.end())

    Now printing the sorted vector:

       for(std::vector< std::string>::iterator i = vec.begin(); i != vec.end(); ++i)
    {
        std::cout<< *i <<std::endl;
    }
    
    0 讨论(0)
提交回复
热议问题