选择C ++的begin()和end()

时间:2018-02-13 12:16:15

标签: c++

我有一个项目要求我读取和排序某个列从.csv文件中读取的值。 我在C ++中使用算法库,readonly SQLiteAsyncConnection database; 该库具有我计划使用的函数#include <algorithm>。 它要求我指定开始和结束,例如,对于称为vect的2d向量,它需要sort()以及vect.begin()。 我的问题是,是否可以为sort()函数指定确切的起始位置和结束位置。这就像从vect [1] [0]开始,到vect [9] [9]结束。

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

我为了讨论而假设您正在使用std::vector<std::vector<int> >。同样的讨论适用于其他类型的2D矢量。

如果您想对单个int进行排序,以便在std::vector<std::vector<int> >内对其进行排序,那么就无法直接进行排序。{p>没有迭代器可以直接从遍历所有嵌套std::vector<std::vector<int>>的{​​{1}}获得。

一种方法可能是将临时副本设置为int(即创建展平的1D向量),对其进行排序,然后将元素复制回来。例如;

std::vector<int>

std::vector<std:vector<int> > vec; // populate vec somehow std::vector<int> elements(0); // create a single std::vector<int> from the vector<vector<int>> by // appending the vector<int>s end to end for (const auto &row : vec) { elements.insert(elements.end(), row.begin(), row.end()); } std::sort(elements.begin(), elements.end()); // sort in ascending order // now copy the sorted elements back auto start = elements.begin(); for (auto &row : vec) // non-const here since we seek to change the vector<int>s within vec { auto end = start + row.size(); std::copy(start, end, row.begin()); start = end; } row.size()的最后一个循环中的恶作剧处理row.begin() vector<int>vec的大小不同,因此会更改

 {{5,6,7}, {1,2}, {3,4,8}}

 {{1,2,3}, {4, 5}, {6,7,8}}

而不是像

那样的其他东西
 {{1,2}, {3,4,5}, {6, 7, 8}};     //   vector<int>s resized

如果假设所有内部向量具有相同的大小,那么可以简化一些事情。

或者,您可以尝试手动滚动具有随机访问迭代器的所有属性的struct / class类型(这是std::sort()所需的)。该结构(或其成员函数/运算符)将需要跟踪它所引用的哪个std::vector<int>(在2D向量内)和该向量内的特定int。这将是适度棘手的(例如,如果自定义迭代器引用特定std::vector<int>的最后一个元素,则递增它必须给出引用下一个vector<int>的第一个元素的结果。 std::vector<std::vector<int> >根本没有任何内置功能可以直接为您提供这样的迭代器。我将滚动这样的自定义迭代器作为练习。

答案 1 :(得分:0)

鉴于你知道迭代的顺序,你可以指定相对于开始的元素。

vect.begin()     // first element
vect.begin() + 2 // third element

所以如果你只想排序第一个让我们说10个元素使用以下内容:

std::sort(vect.begin(), vect.begin() + 10);

更多here

正如其他人已经提到的,你无法真正对2D矢量进行排序。因此,您要么单独对每个向量进行排序,要么将其展平为1D向量,并使用索引计算进行2D解释。

答案 2 :(得分:0)

  1. 将您排序的列加载到std::vector< std::pair > index;并设置
    • 第一个元素作为vector(0,1,2,...)
    • 中的行索引
    • 第二个元素将是行和列中的值
  2. 使用此问题对该对中的第二项进行排序:How do I sort a vector of pairs based on the second element of the pair?
  3. 现在您的行索引按向量&lt;中的列值排序了对&gt;并且您可以创建新的2d向量并使用原始2d向量中的行填充其行。在每次迭代中,使用index向量中的第一个项目选择原始2D向量中具有索引的行。