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

前端 未结 7 2060
一向
一向 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 22:48

    What is the question exactly? It seems everything is already there.

    However, you should probably use std::cout << *i << std::endl;

    1. i is an iterator == pointer to the data in the container, so * is needed
    2. c_str() is a function of std::string and not a variable

    The problems in your code do not relate to your question?

    Some hints for you:

    • std::vector also overrides [] operator, so you can instead save the iterator hassle and use it like an array (iterate from 0 to vector.size()).
    • You could use std::set instead, which has automatically sorting on insertion (binary tree), so you save the extra sorting.
    • Using a functor makes your output even more fun: copy(V.begin(), V.end(), ostream_iterator(cout, "\n"));

提交回复
热议问题