我想用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 …将a的每个值重置std::vector<int>为0并保持向量初始大小的最快方法是什么?
带[]运算符的for循环?
经过对valgrind的大量调查后,我得出结论,std :: vector制作了你想要push_back的对象的副本.
这是真的吗?没有副本,向量不能保留对象的引用或指针?
谢谢
我很喜欢矢量.他们很快,很快.但我知道这个叫做valarray的东西存在.为什么我会使用valarray而不是矢量?我知道valarray有一些语法糖,但除此之外,它们什么时候有用?
我需要复制std::set到std::vector:
std::set <double> input;
input.insert(5);
input.insert(6);
std::vector <double> output;
std::copy(input.begin(), input.end(), output.begin()); //Error: Vector iterator not dereferencable
问题出在哪儿?
如果我有一对矢量:
std::vector<std::pair<int, int> > vec;
是否有简单的方法根据对的第二个元素按递增顺序对列表进行排序?
我知道我可以编写一个可以完成工作的小函数对象,但是有没有办法使用STL的现有部分并std::less直接进行工作?
编辑:我明白我可以编写一个单独的函数或类来传递给第三个参数进行排序.问题是我是否可以用标准的东西来构建它.我真的看起来像:
std::sort(vec.begin(), vec.end(), std::something_magic<int, int, std::less>());
我有几个大型数组的Java代码,它们永远不会改变它们的大小.它在我的计算机上运行1100毫秒.
我用C++实现了相同的代码并使用了std::vector.
在我的计算机上运行完全相同代码的C++实现的时间是8800毫秒.我做错了什么,以便它慢慢地运行?
基本上代码执行以下操作:
for (int i = 0; i < numberOfCells; ++i) {
        h[i] =  h[i] + 1;
        floodedCells[i] =  !floodedCells[i];
        floodedCellsTimeInterval[i] =  !floodedCellsTimeInterval[i];
        qInflow[i] =  qInflow[i] + 1;
}
它遍历大小约为20000的不同数组.
您可以在以下链接中找到这两种实现:
(在ideone上我只能运行循环400次而不是2000次因为时间限制.但即使在这里也有三次相差)
我正在寻找一种通用的,可重用的方式来改变std::vectorC++中的一个.这就是我目前的做法,但我认为它不是很有效,因为它需要一个中间数组,它需要知道项目类型(在这个例子中是DeckCard):
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);
}
我正在使用一个外部库,它在某些时候给了我一个指向整数数组和大小的原始指针。
现在我想使用std::vector来访问和修改这些值,而不是使用原始指针访问它们。
这是一个解释这一点的人为示例:
size_t size = 0;
int * data = get_data_from_library(size);   // raw data from library {5,3,2,1,4}, size gets filled in
std::vector<int> v = ????;                  // pseudo vector to be used to access the raw data
std::sort(v.begin(), v.end());              // sort raw data in place
for (int i = 0; i < 5; i++)
{
  std::cout << data[i] << "\n";             // display sorted raw data 
}
预期输出:
1
2
3
4
5
原因是我需要<algorithm>在该数据上应用算法(排序、交换元素等)。
在另一方面改变这种载体的大小将永远不会改变,因此push_back, …