C++ 访问结构元素。可以像向量一样访问吗?
我有以下使用结构的示例(简化):C++ 访问结构元素。可以像向量一样访问吗?,c++,vector,struct,C++,Vector,Struct,我有以下使用结构的示例(简化): #include <iostream> #include <algorithm> #include <time.h> using namespace std; struct s_str { int a=1,b=2,c=3; }; int main(void) { s_str str; int sel; srand(time(NULL)); //init
#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;
struct s_str
{
int a=1,b=2,c=3;
};
int main(void)
{
s_str str;
int sel;
srand(time(NULL)); //initialize random seed
sel = rand() % (3); //generate a random number between 0 and 2
cout << "sel: " << sel << endl;
cout << "str: " << str.??? << endl;//I was wondering to output a, b or c
return 0; //depending whether sel=0,1,2respectively.
}
我试着用两个操作符来实现它,但它没有编译,因为它们重载了。一般来说,没有
如果结构元素的唯一区别在于其索引,请在结构中定义向量或数组
如果有时要按名称引用元素,有时要按位置引用元素,请为结构定义一个
运算符[](int)
。如果结构中只有几个int,最简单的方法是:
struct s_str
{
int a = 1, b = 2, c = 3;
int& operator[] (size_t t) {
assert(t<3); // assumption for the following to return a meaningful value
return (t == 0 ? a : (t == 1 ? b : c));
}
};
struct s_str
{
INTA=1,b=2,c=3;
整数和运算符[](大小){
assert(t如前所述,如果不提供特定的映射和索引运算符,则无法执行此操作。如下所示:
intmain(){
s_str s;
如果不将索引映射到成员,则无法进行移植。谢谢大家的回答!只需将所有内容都放在一行即可。当然,if链或开关也可以是备选方案,尤其是在您有更多变量的情况下。条件运算符:“如果第二个和第三个操作数是相同值类别的glvalues,并且具有相同的类型,则结果为该类型和值类别”(Std 5.16 pt.4)@Christophe注意:对于超出范围的情况,您的解决方案总是返回c
!@πάνταῥεῖ 是的!我的信息不是绝对使用条件运算符,而是使用返回引用的运算符[]。正如我在上面的评论中所述,对于更复杂的要求,如果链和开关更合适的话。:-)没有对错之分。要求是:SEL数,即,如果SEL=0,STR.B如果SEL=1,Struc C如果SEL=3。“但是我可以提出断言以使假设明确。我的C++是生锈的,但是我相信如果您定义<代码>操作符[]
返回int&
然后您也可以在作业的左侧使用它。非常好!我同意这是最通用、最可靠的解决方案。衷心感谢=)@ilovemissting De Nada!;)
struct s_str
{
int a = 1, b = 2, c = 3;
int& operator[] (size_t t) {
assert(t<3); // assumption for the following to return a meaningful value
return (t == 0 ? a : (t == 1 ? b : c));
}
};
cout << "str: " << str[sel] << endl;
str[sel] = 9;
cout << "a,b,c=" << str.a << "," << str.b << "," << str.c << endl;
struct s_str
{
int a=1,b=2,c=3;
int& operator[](int index) {
switch(index) {
case 0:
return a;
case 1:
return b;
case 2:
return c;
default:
throw std::out_of_range("s_str: Index out of range.");
break;
}
}
};
int main() {
s_str s;
cout << s[0] << ", " << s[1] << ", " << s[2] << endl;
// cout << s[42] << endl; // Uncomment to see it fail.
return 0;
}