【问题标题】:How do I convert from arrays to STL vectors?如何从数组转换为 STL 向量?
【发布时间】:2021-10-22 23:29:50
【问题描述】:

在我的课堂上,我们最近接触了 STL 向量。我的教授给了我们一个使用数组的程序,我们将把它转换为使用std::vectors。他希望我们使用迭代器,因此我们不允许使用方括号、push_back 成员函数或at 成员函数。这是我必须转换的程序中的一个 for 循环:

void readData(Highscore highScores[], int size)
{
    for(int index = 0; index < size; index++)
    {
        cout << "Enter the name for score #" << (index + 1) << ": ";
        cin.getline(highScores[index].name, MAX_NAME_SIZE, '\n');
        
        cout << "Enter the score for score #" << (index + 1) << ": ";
        cin >> highScores[index].score;
        cin.ignore();
    }
    cout << endl;
}
`

我只是不太了解如何转换它们。到目前为止,我有点能够得到这个:for (vector &lt;Highscore&gt; :: iterator num = scores.begin(); num &lt; scores.end(); num++)for for 循环。这对我来说不太有意义,所以我希望我能获得更多提示,甚至更多关于如何转换它们的信息。我不想要答案,只是一个提示。谢谢! (如果它有任何帮助,这是我要 to 转换的程序,这是我们必须使用的四个标题

void getVectorSize(int& size);
void readData(vector<Highscore>& scores);
void sortData(vector<Highscore>& scores);
vector<Highscore>::iterator findLocationOfLargest(
                                const vector<Highscore>::iterator startingLocation,
                                const vector<Highscore>::iterator endingLocation);
void displayData(const vector<Highscore>& scores);

以上是必须使用的标题(必须使用这些而不是程序标题)

#include <iostream>
using namespace std;

const int MAX_NAME_SIZE = 24;

struct Highscore{
    char name[MAX_NAME_SIZE];
    int score;
};

void getArraySize(int& size);
void readData(Highscore highScores[], int size);
void sortData(Highscore highScores[], int size);
int findIndexOfLargest(const Highscore highScores[], int startingIndex, int size);
void displayData(const Highscore highScores[], int size);

int main()
{
    Highscore* highScores;
    int size;
    
    getArraySize(size);
    
    highScores = new Highscore[size];
    
    readData(highScores, size);
    sortData(highScores, size);
    displayData(highScores, size);
    
    delete [] highScores;
}



void getArraySize(int& size){
    cout << "How many scores will you enter?: ";
    cin >> size;
    cin.ignore();
}



void readData(Highscore highScores[], int size)
{
    for(int index = 0; index < size; index++)
    {
        cout << "Enter the name for score #" << (index + 1) << ": ";
        cin.getline(highScores[index].name, MAX_NAME_SIZE, '\n');
        
        cout << "Enter the score for score #" << (index + 1) << ": ";
        cin >> highScores[index].score;
        cin.ignore();
    }
    cout << endl;
}



void sortData(Highscore highScores[], int numItems) {
    for (int count = 0; count < numItems - 1; count++){
        swap(highScores[findIndexOfLargest(highScores, count, numItems)],
             highScores[count]);

    }
}



int findIndexOfLargest(const Highscore highScores[], int startingIndex, int numItems){
    int indexOfLargest = startingIndex;
    
    for (int count = startingIndex + 1; count < numItems; count++){
        if (highScores[count].score > highScores[indexOfLargest].score){
            indexOfLargest = count;
        }
    }
    return indexOfLargest;
}



void displayData(const Highscore highScores[], int size)
{
    cout << "Top Scorers: " << endl;
    for(int index = 0; index < size; index++)
    {
        cout << highScores[index].name << ": " << highScores[index].score << endl;
    }
}

【问题讨论】:

  • 这是在您发布的功能之后使用,还是代替?由于看起来可能不是,因此您的向量在“读取”它们之前将没有元素,因此不要对其进行迭代。使用具有最大大小的类似 for 循环,然后考虑 push_back 和 Highscore 构造函数。
  • 是否要求每个函数使用相同的参数和返回类型? (除了向量而不是数组?)例如,您可以使用std::vector&lt;Highscore&gt; readData(int size) 吗?还是应该将该函数保留为 void return 并通过引用传递向量?
  • @chrisb2244 该函数应保留为通过引用传递向量的 void 返回。
  • @JamIT 很抱歉,他不希望我们使用它,因为他强调他希望我们使用迭代器。很抱歉造成混乱。
  • 那(和解释)是绝对必须包含在问题中的。否则,人们将来会偶然发现问题及其答案并玩几轮WTF?!?

标签: c++ stl iterator


【解决方案1】:

您可能正在寻找两件事中的一件。 如果你想在向量中添加一些东西,函数是 push_back

vecScores.push_back(value) ; //in a for loop.

https://www.cplusplus.com/reference/vector/vector/push_back/

如果你想在地图上添加一些东西,你可以使用

的形式
mapScore[index]=value ; // in a for loop.

https://www.cplusplus.com/reference/map/map/operator[]/

【讨论】:

  • 我忘了在帖子中提到这一点,但我限制使用方括号、push_back() 函数、at() 函数等。可能还有其他方法吗?
  • 您可以使用 vecScores.assign 示例,请参阅cplusplus.com/reference/vector/vector/assign 请参阅示例的第三个.assign 部分。希望您的作业允许这样做! (双关语)
  • 好吧,至少,您必须使用 vecScores.resize 来设置大小。然后,您可以使用 iter = begin() 获取迭代器并使用 *iter 进行设置。你可以做 ++iter 去下一个然后设置它,等等,一直到 != end()。见cplusplus.com/reference/vector/vector/begin祝你一切顺利。我周末出去了!
【解决方案2】:

我会这样做,也习惯于输入 std:: Why is "using namespace std;" considered bad practice?

还要小心有符号/无符号,要精确。 如果某些东西不能有负值,请使用无符号类型(或 size_t)

#include <iostream>
#include <string>
#include <vector>

struct HighScore
{
    std::string name;
    unsigned int score;
};

// use size_t for sizes (value will always >0)
std::vector<HighScore> GetHighScores(size_t size)
{
    std::vector<HighScore> highScores;
    std::string points;

    for (size_t index = 0; index < size; index++)
    {
        HighScore score;
    
        std::cout << "Enter the name for score #" << (index + 1) << ": ";
        std::cin >> score.name;
            
        std::cout << "Enter the score for score #" << (index + 1) << ": ";
        std::cin >> points;

        // convert string to int
        score.score = static_cast<unsigned int>(std::atoi(points.c_str()));
    
        highScores.push_back(score);
    }
    std::cout << std::endl;

    return highScores;
}


int main()
{
    auto highScores = GetHighScores(3);
    return 1;
}

【讨论】:

    【解决方案3】:

    可能你的教授希望你写这样的东西:

    void readData(std::vector<Highscore>& highScores)
    {
        for (auto it = highScores.begin(); it != highScores.end(); ++it) {
            cout << "Enter the name for score #" << std::distance(highScores.begin(), it) << ": ";
            cin.getline(it->name, MAX_NAME_SIZE, '\n');
    
            cout << "Enter the score for score #" << std::distance(highScores.begin(), it) << ": ";
            cin >> it->score;
            cin.ignore();
        }
        cout << endl;
    }
    

    其中it 是通过++ithighScores.begin() 递增到highScores.end() 之前的迭代器;然后您通过it-&gt;<i>member</i> 访问highScores 的元素“指向”it 的成员。

    Here's a complete demo.


    顺便说一句,考虑到你的教授有多喜欢void(some_type&amp;) 函数(以及using namespace std;,如果这不是你自己的想法的话),我怀疑你有很多东西可以向他学习。你最好买一本好书。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 2011-02-16
      相关资源
      最近更新 更多