stdvector

Concatenating two std::vectors

半世苍凉 提交于 2019-11-25 23:48:00
问题 How do I concatenate two std::vector s? 回答1: vector1.insert( vector1.end(), vector2.begin(), vector2.end() ); 回答2: If you are using C++11, and wish to move the elements rather than merely copying them, you can use std::move_iterator along with insert (or copy): #include <vector> #include <iostream> #include <iterator> int main(int argc, char** argv) { std::vector<int> dest{1,2,3,4,5}; std::vector<int> src{6,7,8,9,10}; // Move elements from src to dest. // src is left in undefined but safe-to

How to print out the contents of a vector?

蹲街弑〆低调 提交于 2019-11-25 23:13:34
问题 I want to print out the contents of a vector in C++, here is what I have: #include <iostream> #include <fstream> #include <string> #include <cmath> #include <vector> #include <sstream> #include <cstdio> using namespace std; int main() { ifstream file(\"maze.txt\"); if (file) { vector<char> vec(istreambuf_iterator<char>(file), (istreambuf_iterator<char>())); vector<char> path; int x = 17; char entrance = vec.at(16); char firstsquare = vec.at(x); if (entrance == \'S\') { path.push_back(entrance

How do I sort a vector of pairs based on the second element of the pair?

寵の児 提交于 2019-11-25 20:27:11
If I have a vector of pairs: std::vector<std::pair<int, int> > vec; Is there and easy way to sort the list in increasing order based on the second element of the pair? I know I can write a little function object that will do the work, but is there a way to use existing parts of the STL and std::less to do the work directly? EDIT: I understand that I can write a separate function or class to pass to the third argument to sort. The question is whether or not I can build it out of standard stuff. I'd really something that looks like: std::sort(vec.begin(), vec.end(), std::something_magic<int, int

How to shuffle a std::vector?

丶灬走出姿态 提交于 2019-11-25 19:24:38
I am looking for a generic, reusable way to shuffle a std::vector in C++. This is how I currently do it, but I think it's not very efficient because it needs an intermediate array and it needs to know the item type (DeckCard in this example): srand(time(NULL)); cards_.clear(); while (temp.size() > 0) { int idx = rand() % temp.size(); DeckCard* card = temp[idx]; cards_.push_back(card); temp.erase(temp.begin() + idx); } From C++11 onwards, you should prefer: #include <algorithm> #include <random> auto rng = std::default_random_engine {}; std::shuffle(std::begin(cards_), std::end(cards_), rng);