我应该用吗?
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
Run Code Online (Sandbox Code Playgroud)
要么
std::sort(numbers.rbegin(), numbers.rend()); // note: reverse iterators
Run Code Online (Sandbox Code Playgroud)
按降序对矢量进行排序?一种方法或另一种方法有任何好处或缺点吗?
假设我有一个std::vector(让我们称之为myVec)大小N.构造由元素X到Y的副本组成的新向量的最简单方法是什么,其中0 <= X <= Y <= N-1?例如,myVec [100000]通过myVec [100999]大小的向量150000.
如果使用向量无法有效地完成此操作,是否应该使用另一种STL数据类型?
C++中的a std::vector和a有什么区别std::array?什么时候应该优先于另一个?各自的优点和缺点是什么?我的所有教科书都列出了它们是如何相同的.
假设我有一个嵌套在数据帧中的一个或两个级别的向量.是否有快速而肮脏的方式来访问最后一个值,而不使用该length()功能?PERL的$#特殊变量是什么?
所以我想要像:
dat$vec1$vec2[$#]
Run Code Online (Sandbox Code Playgroud)
代替
dat$vec1$vec2[length(dat$vec1$vec2)]
Run Code Online (Sandbox Code Playgroud) 我需要带有可能包含大量元素的C++向量,擦除重复项并对其进行排序.
我目前有以下代码,但它不起作用.
vec.erase(
std::unique(vec.begin(), vec.end()),
vec.end());
std::sort(vec.begin(), vec.end());
Run Code Online (Sandbox Code Playgroud)
我怎样才能正确地做到这一点?
此外,首先擦除重复项(类似于上面编码)或首先执行排序是否更快?如果我首先执行排序,是否保证在std::unique执行后保持排序?
或者还有另一种(也许是更有效的)方法来做这一切吗?
我想用C++打印出一个向量的内容,这就是我所拥有的:
#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);
}
for (x = 17; isalpha(firstsquare); x++) {
path.push_back(firstsquare);
}
for (int i = 0; i < path.size(); i++) {
cout << path[i] << " ";
}
cout << endl;
return …Run Code Online (Sandbox Code Playgroud) 可能重复:
如何在std :: vector中查找项目?
有什么东西<algorithm>可以让你检查std :: container是否包含某些内容?或者,制作一个方法,例如:
if(a.x == b.x && a.y == b.y)
return true;
return false;
Run Code Online (Sandbox Code Playgroud)
这可以只std::map使用密钥吗?
谢谢
vector<int> myVector;
Run Code Online (Sandbox Code Playgroud)
并且让我们说向量中的值是这个(按此顺序):
5 9 2 8 0 7
Run Code Online (Sandbox Code Playgroud)
如果我想删除包含值"8"的元素,我想我会这样做:
myVector.erase(myVector.begin()+4);
Run Code Online (Sandbox Code Playgroud)
因为那会抹掉第4个元素.但有没有办法根据值"8"擦除元素?喜欢:
myVector.eraseElementWhoseValueIs(8);
Run Code Online (Sandbox Code Playgroud)
或者我只是需要遍历所有的向量元素并测试它们的值?
当我启用C++ 11时,我在一个小的C++片段中发现了一个有趣的性能回归:
#include <vector>
struct Item
{
int a;
int b;
};
int main()
{
const std::size_t num_items = 10000000;
std::vector<Item> container;
container.reserve(num_items);
for (std::size_t i = 0; i < num_items; ++i) {
container.push_back(Item());
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用g ++(GCC)4.8.2 20131219(预发行版)和C++ 03,我得到:
milian:/tmp$ g++ -O3 main.cpp && perf stat -r 10 ./a.out
Performance counter stats for './a.out' (10 runs):
35.206824 task-clock # 0.988 CPUs utilized ( +- 1.23% )
4 context-switches # 0.116 K/sec ( +- 4.38% )
0 cpu-migrations …Run Code Online (Sandbox Code Playgroud)