gpt4 book ai didi

c++ - 将多个整数添加到一个 vector 索引? 'Cout' 不工作

转载 作者:行者123 更新时间:2023-11-28 02:07:08 24 4
gpt4 key购买 nike

所以我在这里找到了我正在使用的这段代码:

#include <iostream>
#include <cstdlib>
#include <vector>

using namespace std;

struct Something{
int x;
int y;
};

int main()
{
vector <Something> v;
int x, y;
cin >> x >> y;

Something temp;
temp.x = x;
temp.y = y;
v.push_back(temp);

for (size_t i = 0; i < v.size(); i++)
{
cout << v[i] << endl; // Error: No operator "<<" matches these operands. Operand types are std::ostream << Something
}
}

基本上,我试图将多个整数放入一个 vector 索引中。当我尝试打印 vector 的内容时,cout 不工作。

首先,我是否正确地执行了这个多重 int 操作?我对 C++ 比较陌生。

如果我这样做是对的,关于为什么 cout 不起作用的任何想法?我还尝试了 v.push_back({x,y}) 但没有用。知道 cout 发生了什么吗?非常感谢。


编辑:到目前为止非常感谢。我还有一个问题。如果我要修改我的代码以接受多个输入,然后希望 vector 中的所有内容都根据“y”从大到小排序。

示例(原始 vector 内容(x,y))

12 4
1 2
4 10
1 1
1 2

根据'y'(从大到小)排序

4 10
12 4
1 2
1 2
1 1

我知道如何进行常规排序,但不知道如何根据第二个数字 (y) 进行排序。我怎么做?非常感谢。

最佳答案

正如错误所说,没有重载 operator<<为您的结构声明的函数。

有三种可能的解决方案:第一种是输出结构体的每个成员,比如

std::cout << v[i].x << ' ' << v[i].y << '\n';

另一种是创建一个执行上述操作的函数,作为成员函数或非成员函数。

第三个解决方案是创建一个重载的 operator<<结构函数:

std::ostream& operator<<(std::ostream& os, Something const& something)
{
return os << something.x << ' ' something.y;
}

我推荐你find a good beginners book on C++并阅读有关输出、结构和类以及运算符和运算符重载的章节。

关于c++ - 将多个整数添加到一个 vector 索引? 'Cout' 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37065214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com