我试图根据特定的条件从地图中删除一系列元素。 我如何使用STLalgorithm做到这一点? 最初我想过使用remove_if但是这是不可能的,因为remove_if不适用于关联容器。 有没有任何“remove_if”等效algorithm适用于map? 作为一个简单的选项,我想通过循环地图和擦除。 但是通过地图循环并擦除一个安全的选项?(因为迭代器在擦除后变得无效) 我用下面的例子: bool predicate(const std::pair<int,std::string>& x) { return x.first > 2; } int main(void) { std::map<int, std::string> aMap; aMap[2] = "two"; aMap[3] = "three"; aMap[4] = "four"; aMap[5] = "five"; aMap[6] = "six"; // does not work, an error // std::remove_if(aMap.begin(), aMap.end(), predicate); std::map<int, std::string>::iterator iter = aMap.begin(); std::map<int, std::string>::iterator […]
我试图使用std::vector作为char数组。 我的函数需要一个void指针: void process_data(const void *data); 在我简单地使用这个代码之前: char something[] = "my data here"; process_data(something); 其中按预期工作。 但是现在我需要std::vector的dynamic性,所以我尝试了这个代码: vector<char> something; *cut* process_data(something); 问题是,如何将char向量传递给我的函数,以便我可以访问向量原始数据(不pipe是哪种格式 – 浮动等)? 我试过这个: process_data(&something); 和这个: process_data(&something.begin()); 但是它返回了一个指向乱码数据的指针,后者给出警告: warning C4238: nonstandard extension used : class rvalue used as lvalue 。
一本教科书我注意到,你可以提供自己的实现标准库函数,如swap(x,y)通过模板专门化function重载。 这对任何可以从除了赋值交换以外的其他types都有用的types是有用的,比如STL containers (已经有了交换,我知道)。 我的问题是: 有什么更好的:模板专门化给你的专门的交换实现,或function重载,提供了你想使用没有模板的确切参数? 为什么更好? 或者如果他们是平等的,为什么呢?
是否有指导如何写一个新的容器,其行为将像任何STL容器?
假设我有2个标准向量: vector<int> a; vector<int> b; 我们还要说,这两者都有大约30个元素。 如何将向量b添加到向量a的末尾? 肮脏的方式将通过b迭代,并通过vector<int>::push_back()添加每个元素,但我不想这样做!
我想复制向量的内容,并希望它们被添加到原始向量的末尾,即v[i]=v[i+n] for i=0,2,…,n-1 我正在寻找一个很好的方式来做到这一点,而不是一个循环。 我看到std::vector::insert但迭代版本禁止迭代器*this (即行为是未定义的)。 我也尝试了std::copy如下(但它导致分段错误): copy( xx.begin(), xx.end(), xx.end());
我有几个std::vector ,都是相同的长度。 我想对这些向量之一进行sorting,并将相同的转换应用于所有其他向量。 有没有一个干净的方式做到这一点? (最好使用STL或Boost)? 一些向量保存int s,其中一些std::strings 。 伪代码: std::vector<int> Index = { 3, 1, 2 }; std::vector<std::string> Values = { "Third", "First", "Second" }; Transformation = sort(Index); Index is now { 1, 2, 3}; … magic happens as Transformation is applied to Values … Values are now { "First", "Second", "Third" };
以下所有的陈述是正确的吗? vector<Type> vect; //allocates vect on stack and each of the Type (using std::allocator) also will be on the stack vector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stack vector<Type*> vect; //vect will be on stack and Type* will be on heap. 在vector或任何其他STL容器中Type的内存是如何分配的?
在STLalgorithm中启用swap的正确方法是什么? 1)会员swap 。 std::swap是否使用SFINAE技巧来使用成员swap 。 2)在相同的命名空间中独立swap 。 3)部分专业化的std::swap 。 4)以上全部。 谢谢。 编辑:看起来我没有清楚地说出我的问题。 基本上,我有一个模板类,我需要STLalgorithm使用我为这个类写的(高效)交换方法。
我想避免不必要的副本。 我正在瞄准的东西: std::ifstream testFile( "testfile", "rb" ); std::vector<char> fileContents; int fileSize = getFileSize( testFile ); fileContents.reserve( fileSize ); testFile.read( &fileContents[0], fileSize ); (这不起作用,因为reserve实际上并没有插入任何东西,所以我不能访问[0] )。 当然, std::vector<char> fileContents(fileSize)可以工作,但是初始化所有元素会有开销( fileSize可能比较大)。 相同的resize() 。 这个问题并不那么重要,这将是开销。 相反,我只是想知道是否有另一种方式。